日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

解讀golang中的const常量和iota_Golang

作者:liberg ? 更新時間: 2023-02-05 編程語言

golang中的const常量和iota

golang中通過var定義變量,通過const定義常量。

常量只能是基本的簡單值類型,常量一經定義其值不可修改(類比Java中的final)。

const (
?? ?MaxInt = int(^uint(0) >> 1)
?? ?MinInt = -MaxInt - 1
)
const PI = 3.14
PI = 3.14159//編譯錯誤,Cannot assign to PI
  • iota是一個特殊常量,可以認為是一個可以被編譯器修改的常量。
  • iota在const關鍵字出現時將被重置為0,const中每新增一行常量聲明將使 iota 計數加1,因此iota可作為const 語句塊中的行索引。
const (
?? ?a ? = 1 ? ? ? ? ? ? ? ? ?//1 (iota=0)
?? ?b ? ? ? ? ? ? ? ? ? ? ? ?//1 (iota=1,同上一行,相當于寫b=1)
?? ?c ? = b + iota ? ? ? ? ? //3 (iota=2,b=1)
?? ?d ? ? ? ? ? ? ? ? ? ? ? ?//4 (iota=3,同上一行,相當于寫b+iota,b=1)
?? ?e ? ? ? ? ? ? ? ? ? ? ? ?//5 (iota=4,同上一行,相當于寫b+iota,b=1)
?? ?f ? = "last one but one" // ?(iota=5)
?? ?end = iota ? ? ? ? ? ? ? //6 (iota=6)
)
fmt.Println(a, reflect.TypeOf(a))
fmt.Println(b, reflect.TypeOf(b))
fmt.Println(c, reflect.TypeOf(c))
fmt.Println(d, reflect.TypeOf(d))
fmt.Println(e, reflect.TypeOf(e))
fmt.Println(f, reflect.TypeOf(f))
fmt.Println(end, reflect.TypeOf(end))
/*?
輸出:
1 int
1 int
3 int
4 int
5 int
last one but one string
6 int
*/

golang定義常量

在所有的編程語言當中常量都代表一個固定的值,一旦常量被定義則無法修改。在Golang中使用const關鍵字進行常量聲明。

定義常量

Golang定義常規類型的常量可以忽略類型。

const SUCCESS = true
const FAIL = false

定義多個相同類型的常量

const (
CONST1 = 0
CONST2 = 1
CONST3 = 2
)

定義特定類型的常量

定義特定類型的常量需要根據實際情況來決定。

假如我們現在用常量來聲明用戶的三個基本狀態(正常,禁止登錄,刪除),一般這種情況我們會首先聲明一個用戶狀態的類型。

聲明用戶狀態類型:

type UserStatus int

定義用戶狀態常量:

const (
USER_STATUS_NORMAL UserStatus = iota
USER_STATUS_DISABLED_LOGIN
USER_STATUS_DELETE
)

完整示例:

package user
//Status 用戶類型.
type Status int
const (
//STATUS_NORMAL 狀態正常
STATUS_NORMAL Status = iota
//STATUS_DISABLED_LOGIN 禁止登錄.
STATUS_DISABLED_LOGIN
//STATUS_DELETE 已刪除.
STATUS_DELETE
)

總結

原文鏈接:https://blog.csdn.net/linysuccess/article/details/102639706

欄目分類
最近更新