乐闻世界logo
搜索文章和话题

Golang : Is conversion between different struct types possible?

1个答案

1

In Go, conversion between different struct types is not directly supported. The Go type system is strict and requires explicit type conversion. This means that even if two structs have identical fields, they are treated as distinct types and cannot be directly converted.

However, you can implement this functionality by writing code. Typically, there are two approaches to achieve struct conversion:

  1. Manual Conversion: Create a new instance of the target struct and copy the values of each field from the source struct to the corresponding fields in the target struct. This method is straightforward but requires manual handling of each field, which can be tedious when the struct has many fields.

  2. Using Reflection: By leveraging Go's reflection capabilities, you can dynamically retrieve object information at runtime and perform more flexible conversions. This approach automates field assignment but sacrifices some performance and type safety.

Example

Consider the following two structs:

go
type Person struct { Name string Age int } type User struct { Name string Age int }

Manual Conversion

go
func ConvertPersonToUser(p Person) User { return User{ Name: p.Name, Age: p.Age, } }

Using Reflection

go
import "reflect" func ConvertByReflection(s1 interface{}, s2 interface{}) { s1Val := reflect.ValueOf(s1).Elem() s2Val := reflect.ValueOf(s2).Elem() s1Type := s1Val.Type() for i := 0; i < s1Val.NumField(); i++ { field := s1Type.Field(i) s2Field := s2Val.FieldByName(field.Name) if s2Field.IsValid() && s2Field.Type() == field.Type { s2Field.Set(s1Val.Field(i)) } } } // Usage example person := Person{Name: "Alice", Age: 30} user := User{} ConvertByReflection(&person, &user)

Conclusion

Although Go does not directly support conversion between different struct types, it can be achieved using the methods described above. The choice of method depends on the specific use case, requiring a trade-off between development efficiency, performance, and code maintainability. In performance-sensitive scenarios, manual conversion is typically the better choice. When dealing with multiple different structs and complex structures, using reflection may be more efficient.

2024年10月28日 20:50 回复

你的答案