Home > Article > Backend Development > How Can I Store Both Strings and Integers in a Go Struct Using an Interface?
Combining String and Integer Values in a Go Struct: Using an Interface
In Go, you may encounter scenarios where you need a data structure to store both string and integer values. Consider the following struct definition:
type testCase struct { input string isValid bool }
However, you might find it convenient to handle inputs as either strings or integers depending on the use case. To achieve this, you can employ an interface, as shown below:
type Input interface { String() string }
Interface Implementation for String and Integer Types
You can implement the Input interface for both strings and integers:
type StringInput string func (s StringInput) String() string { return string(s) } type IntegerInput int func (i IntegerInput) String() string { return strconv.Itoa(int(i)) }
Using the Input Interface in Your Struct
Now, you can modify your testCase struct to use the Input interface:
type testCase struct { input Input isValid bool }
Sample Code
Here's an example of how you can use this interface to store and retrieve both string and integer values:
package main import ( "fmt" "strconv" ) type Input interface { String() string } type StringInput string func (s StringInput) String() string { return string(s) } type IntegerInput int func (i IntegerInput) String() string { return strconv.Itoa(int(i)) } type testCase struct { input Input isValid bool } func main() { // Create a test case with a string input testString := testCase{ input: StringInput("Hello, world!"), isValid: true, } // Print the input as a string fmt.Println(testString.input.String()) // Output: Hello, world! // Create a test case with an integer input testInt := testCase{ input: IntegerInput(123), isValid: true, } // Print the input as a string fmt.Println(testInt.input.String()) // Output: 123 }
By leveraging the Input interface, you can seamlessly handle both string and integer values in your Go struct, providing greater flexibility and code reusability.
The above is the detailed content of How Can I Store Both Strings and Integers in a Go Struct Using an Interface?. For more information, please follow other related articles on the PHP Chinese website!