1
头图

foreword

This is the first in a series on the top 10 most common mistakes in Go: Unknown enum value. The material comes from Teiva Harsanyi , a Go evangelist and now a senior engineer at Docker.

The source code involved in this article is all open source in: The source code of the top ten common errors in Go , you are welcome to pay attention to the public account and get the latest updates of this series in time.

Scenes

Let's look at the following code example:

 type Status uint32

const (
    StatusOpen Status = iota
    StatusClosed
    StatusUnknown
)

Here we use iota to define an enumeration, and the corresponding enumeration values are:

 StatusOpen = 0
StatusClosed = 1
StatusUnknown = 2

Suppose the data structure in our business code contains enumeration types, such as the following example:

 type Request struct {
    ID        int    `json:"Id"`
    Timestamp int    `json:"Timestamp"`
    Status    Status `json:"Status"`
}

We need to deserialize the received JSON request to Request struct type.

 {
  "Id": 1234,
  "Timestamp": 1563362390,
  "Status": 0
}

For the above JSON request data, the Status field in the --- Request structure will be parsed as 0, which corresponds to StatusOpen , as expected.

But if the Status field is not passed for various reasons, for the following JSON request

 {
  "Id": 1235,
  "Timestamp": 1563362390
}

When deserializing this JSON request to Request structure type, because there is no Status field in the JSON string, so Request Status the structure Status The value of the field will be zero, which is the zero value of uint32 . At this time, the value of the Status field is still StatusOpen instead of the expected StatusUnknown .

Best Practices

So the best practice for enumeration values is to set the unknown value of the enumeration to 0.

 type Status uint32

const (
    StatusUnknown Status = iota
    StatusOpen
    StatusClosed
)

After this design, if the Status Status in the deserialized Request structure is StatusUnknown , as expected.

open source address

Articles and sample code are open sourced on GitHub: Beginner, Intermediate, and Advanced Tutorials in Go .

Official account: coding advanced. Follow the official account to get the latest Go interview questions and technology stacks.

Personal website: Jincheng's Blog .

Zhihu: Wuji .

References


coding进阶
124 声望18 粉丝