網站首頁 編程語言 正文
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
相關推薦
- 2022-10-29 CSS 漸變彩色字體
- 2023-07-15 uni-app 組件與頁面事件傳值 this.$emit
- 2022-04-01 git clone 失敗
- 2022-11-10 golang?常用定時任務匯總_Golang
- 2022-11-20 Python必知必會之os模塊實例詳解_python
- 2023-03-25 React?數據獲取條件競爭原理解析_React
- 2022-02-12 Flutter項目中有些依賴不支持64位的library的解決方式
- 2022-08-20 Linux常用高頻命令_linux shell
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支