亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Go 中表示狀態

在 Go 中表示狀態

Go
紫衣仙女 2023-07-10 14:43:51
我們一般使用枚舉來表示狀態。例如,在 python 中:我們做class QueueState(Enum):    Enqueued = 1    Processing = 2    Processed = 3    Dequeued = 4我們可以使用QueueState.Enqueued等來訪問它們。其他語言中也存在同樣的行為,例如 Java、C# 等。我的意思是這些狀態有點綁定在 中QueueState。但是當涉及到在 go 中聲明狀態時,我們使用 const 和 iota,例如:type QueueState intconst (    Enqueued QueueState = iota    Processing    Processed    Dequeued)我發現這些狀態(入隊、處理等)與 type 沒有綁定QueueState。要訪問它們,我只需將它們用作常量變量。例如:fmt.Println(Enqueued) // prints 0有沒有辦法可以將這些狀態綁定到類型中并將它們視為枚舉,就像我們在其他編程語言中所做的那樣?例如:我想像這樣使用它們QueueState.Enqueued
查看完整描述

1 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

我發現這些狀態(入隊、處理等)與 type 沒有綁定QueueState。


這并不完全正確。當您打印它的值時,您會看到0打印的內容,因為這是它的數值。該類型QueueState具有int作為其基礎類型。但是Enqueued是類型(在Go PlaygroundQueueState上嘗試一下):


fmt.Printf("%T", Enqueued) // main.QueueState

如果您想“直觀地”將其綁定到類型QueueState,請將其包含在其名稱中:


type QueueState int


const (

? ? QueueStateEnqueued QueueState = iota

? ? QueueStateProcessing

? ? QueueStateProcessed

? ? QueueStateDequeued

)

然后當它被提及時:QueueStateEnqueued它就變得顯而易見了。這種命名“技術”在標準庫中廣泛使用,net/http包中的一些示例:


const (

? ? ? ? MethodGet? ? ?= "GET"

? ? ? ? MethodHead? ? = "HEAD"

? ? ? ? MethodPost? ? = "POST"

? ? ? ? ...

)


const (

? ? ? ? StatusContinue? ? ? ? ? ?= 100 // RFC 7231, 6.2.1

? ? ? ? StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2

? ? ? ? StatusProcessing? ? ? ? ?= 102 // RFC 2518, 10.1


? ? ? ? StatusOK? ? ? ? ? ? ? ? ? ?= 200 // RFC 7231, 6.3.1

? ? ? ? StatusCreated? ? ? ? ? ? ? = 201 // RFC 7231, 6.3.2

? ? ? ? ...

)

如果您想要人類可讀的打印值,請String() string為其定義一個方法:


type QueueState int


func (s QueueState) String() string {

? ? switch s {

? ? case QueueStateEnqueued:

? ? ? ? return "Enqueued"

? ? case QueueStateProcessing:

? ? ? ? return "Processing"

? ? case QueueStateProcessed:

? ? ? ? return "Processed"

? ? case QueueStateDequeued:

? ? ? ? return "Dequeued"

? ? }

? ? return ""

}

然后打印時(在Go Playground上嘗試):


fmt.Println(QueueStateEnqueued) // prints Enqueued

String()是的,提供這種方法并保持更新并不是很方便,因此為什么stringer存在這樣的工具。他們String()以比上述示例實現更緊湊、更高效的方式生成此方法。


還有一個選項可以用作string枚舉的基礎類型,并且枚舉值將用作不帶該方法的字符串表示形式(在Go PlaygroundString()上嘗試):


type QueueState string


const (

? ? QueueStateEnqueued? ?QueueState = "Enqueued"

? ? QueueStateProcessing QueueState = "Processing"

? ? QueueStateProcessed? QueueState = "Processed"

? ? QueueStateDequeued? ?QueueState = "Dequeued"

)


func main() {

? ? fmt.Println(QueueStateEnqueued) // prints Enqueued

}

另請注意,當其他人引用您的枚舉值時,他們會使用包名稱。因此,您可以將枚舉常量放在其指定的包中,例如,稱為queuestate,然后您可以將常量命名為Enqueued等Processing,但是當引用它們時,它將采用等的形式queuestate.Enqueued。queuestate.Processing


另請注意,僅使用常量無法限制類型的值。



查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號