Storing Both String and Int Values in a Go Struct
In Go, it's not possible to store both string and int values directly in a single struct field. This is due to the language's strong type system, which requires variables to have specific, well-defined types.
Possible Solutions
To work around this limitation, you have a few options:
Interface Implementation in Go 1.18 and Beyond
Using an interface, you can create a type that can hold both string and int values. Here's an example:
type Input interface { IsValid() bool Value() interface{} } type TestCaseBool struct { input bool isValid bool } func (tc TestCaseBool) IsValid() bool { return tc.isValid } func (tc TestCaseBool) Value() interface{} { return tc.input }
You can now use the TestCaseBool struct to hold either a boolean value or an empty interface.
Note: This solution requires Go 1.18 or higher to work.
The above is the detailed content of How Can You Store Both String and Int Values in a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!