In golang, interface and structure are two common data types. An interface is an abstract type that defines a set of methods without implementation, while a structure is a concrete type that is used to organize and store data. In actual development, we may need to convert the interface into a structure. This article will introduce two methods for converting interfaces into structures in golang.
1. Use reflection to convert the interface into a structure
In golang, you can use reflection to complete the operation of converting the interface into a structure. Reflection is a powerful mechanism that can dynamically read and modify information such as the value, type, and attributes of a variable at runtime. In reflection, commonly used ones include reflect.Value and reflect.Type.
The specific implementation steps are as follows:
type Person struct { Name string Age int }
type PersonInterface interface { GetName() string GetAge() int }
func ConvertInterfaceToStruct(p PersonInterface) (Person, error) { var person Person value := reflect.ValueOf(p) if value.Kind() == reflect.Ptr && !value.IsNil() { value = value.Elem() if value.Kind() == reflect.Struct { person.Name = value.FieldByName("Name").String() person.Age = int(value.FieldByName("Age").Int()) return person, nil } } return person, fmt.Errorf("invalid type:%v", reflect.TypeOf(p)) }
In this function, first convert the interface type to a reflection value (reflect.Value), and then determine whether the value is a pointer type and non-null. Next, the pointer type is converted to a structure type, and then the Name and Age field values are obtained through reflection, and finally the Person structure type is returned.
func main() { p := &Person{Name: "Tom", Age: 20} fmt.Println(p) if ps, err := ConvertInterfaceToStruct(p); err != nil { log.Fatal(err) } else { fmt.Println(ps) } }
In this test code, create a Person structure pointer, use the implemented ConvertInterfaceToStruct function to convert the pointer type to the Person structure type, and output the result.
2. Use json to implement the interface and convert it into a structure
In golang, json is a common data format. You can serialize an object into a json string through json.Marshal(). You can also deserialize a json string into an object through json.Unmarshal().
The specific implementation steps are as follows:
type Person struct { Name string `json:"name,omitempty"` Age int `json:"age,omitempty"` }
In this structure, the json field name is specified to match its field name in the interface in order to achieve conversion.
type PersonInterface interface { GetName() string GetAge() int }
func ConvertInterfaceToStruct(p PersonInterface) (Person, error) { jsonStr, err := json.Marshal(p) if err != nil { return Person{}, err } var person Person err = json.Unmarshal(jsonStr, &person) if err != nil { return Person{}, err } return person, nil }
In this function, first use json.Marshal() to convert the interface type into a json string, then use json.Unmarshal() to convert it into a Person structure type, and Return the structure.
func main() { p := &Person{Name: "Tom", Age: 20} fmt.Println(p) if ps, err := ConvertInterfaceToStruct(p); err != nil { log.Fatal(err) } else { fmt.Println(ps) } }
In this test code, create a Person structure pointer, use the implemented ConvertInterfaceToStruct function to convert the pointer type to the Person structure type, and output the result.
Summary:
Both of the above two methods can convert the interface type into a structure type, using different methods for implementation. The implementation of the reflection method is relatively low-level and requires type judgment. And field reflection reading, etc., while the json method is relatively simple and clear, you only need to use the json serialization and deserialization methods in golang. The choice of different methods depends on factors such as actual needs and performance.
The above is the detailed content of golang interface to struct. For more information, please follow other related articles on the PHP Chinese website!