go const 常量幾種好習慣用法

一、const 語法介紹

常量是一個簡單值的標識符,在程序運行時,不會被修改的量。
常量中的數據類型只可以是布爾型、數字型(整數型、浮點型和複數)和字符串型。
常量的定義格式:

const identifier [type] = value

你可以省略類型說明符 [type],因爲編譯器可以根據變量的值來推斷其類型。

顯式類型定義:const b string = "abc"
隱式類型定義:const b = "abc"

二、多個統一類型,可以一行申明

多個相同類型的聲明可以簡寫爲:

const c1, c2 = value1, value2

比如

const length, width int = 30, 20

三、把同一類的用 () 括起來

type scope uint8
const (
    scopeInterfaceLocal scope = 0x1
    scopeLinkLocal      scope = 0x2
    scopeAdminLocal     scope = 0x4
    scopeSiteLocal      scope = 0x5
    scopeOrgLocal       scope = 0x8
    scopeGlobal         scope = 0xe
)

這是 go 語言源碼包關於 scope 的幾種常量設置。

四、const 與 iota

iota,特殊常量,可以認爲是一個可以被編譯器修改的常量。

iota 在 const 關鍵字出現時將被重置爲 0(const 內部的第一行之前),const 中每新增一行常量聲明將使 iota 計數一次 (iota 可理解爲 const 語句塊中的行索引)。

iota 可以被用作枚舉值:

const (
    a = iota
    b = iota
    c = iota
)

第一個 iota 等於 0,每當 iota 在新的一行被使用時,它的值都會自動加 1;所以 a=0, b=1, c=2 可以簡寫爲如下形式:

const (
    a = iota
    b
    c
)

注意:iota 自增,必須在同一個 const 以內並且換行,如果不同的 const 是無效的,或者不換號,都是無效的。如下:

const x = iota
const y = iota
const z = iota

const h, i, j = iota, iota, iota

const (
    s = iota
    m = iota
    n = iota
)

const (
    a = iota
    b
    c
)

func TestConst(t *testing.T) {
    t.Log(x, y, z) //0 0 0
    t.Log(h, i, j) //0 0 0
    t.Log(s, m, n) //0 1 2
    t.Log(a, b, c) //0 1 2
}

四種寫法

  1. 每一個一個新的 const,那麼每個都是 0

  2. 一個 const 賦值三個,但在同意後,每個都是 0

  3. 一個 const,賦值三個,換行 iota 遞增

  4. 一個 const,賦值三個,換行 (除第一行,其他行省略) iota 遞增

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/SyVLuOQyI50NBLYJyCI7fQ