3 ms·
That falls over very quickly in go unfortunately because of zero values. type state int const state ( On state = 1 Off state = 2 ) v
by bbatha 6y ago
That falls over very quickly in go unfortunately because of zero values.
type state int
const state (
On state = 1
Off state = 2
)
var s state
fmt.Println(s) // prints 0
- pwdisswordfish2 6y agoI think the parent comment was sarcastic.
- deleted 6y ago[deleted]
- fmakunbound 6y agoGood god.
- orisho 6y agoYou would never initialize an enum like that, since you would use one of the enumerated values instead. That is, after all, the reason behind defining an enum in the first place. When could you end up with an enum that has an invalid value? When you get the value during runtime and typecast from an int. In that case, though, you should obviously have a runtime check that verifies the value is legal. Your example case is something that I can't think of a reason to do. It isn't a case where you would need to be careful and knowledgeable to avoid it - there's just no reason to do it. You would use On and Off instead of defining a variable with this type.
- simon_o 6y ago> It isn't a case where you would need to be careful and knowledgeable to avoid it - there's just no reason to do it. Then why does it compile?
- bbatha 6y agoThis happens all of the time for enums in structs especially during (de)serialization and returning a zero value and an error. func DeserializeState(raw []byte) (State, error) { type Foo struct { State state `json:"state"` Data map[string]string `json:"data"` } f := Foo{} err := json.Unmarshal(&foo, raw) if err != nil { return ???, err } } s := DeserializeState([]byte(`{"data": {"key": "value"}}`) fmt.Println(s) // prints 0 oops