Declaring and Using a Struct Field to Store String and Integer Values
In Go, you may encounter situations where you need to store values of different types within a single struct. While the example struct provided handles string and boolean values, you may also require handling integer (int) input.
However, the Go programming language does not natively support using a single field to store values of different types. Go's type system operates on distinct and immutable types.
To address this, you have two options:
Type Casting:
Multiple Structs:
Note that Go 1.18 will introduce sum types, which would provide a more elegant solution to this problem. However, for earlier versions of Go, you will need to utilize one of the aforementioned approaches.
The above is the detailed content of How to Store String and Integer Values in a Single Struct in Go?. For more information, please follow other related articles on the PHP Chinese website!