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
另請注意,僅使用常量無法限制類型的值。
- 1 回答
- 0 關注
- 137 瀏覽
添加回答
舉報