2.13. 结构转换
g g study,d d up!
3. 结构转换
在Go中,如果两个结构体的字段名和类型相同,那么它们就是相同的类型,可以进行转换。例如:
type User struct {
ID int
Name string
}
type Employee struct {
ID int
Name string
}
func main() {
user := User{ID: 1, Name: "Alice"}
employee := Employee(user)
fmt.Printf("%+v\n", employee)
}
在上面的代码中,我们将User
类型转换为Employee
类型。由于它们具有相同的字段名和类型,所以可以进行转换。输出结果为:{ID:1 Name:Alice}
。
但是,如果两个结构体的字段名和类型不完全相同,那么就需要进行手动转换。例如:
type User struct {
ID int
Name string
Birthday time.Time
}
type Employee struct {
ID int
Name string
HireDate time.Time
}
func main() {
user := User{ID: 1, Name: "Alice", Birthday: time.Now()}
employee := Employee{
ID: user.ID,
Name: user.Name,
HireDate: time.Now(),
}
fmt.Printf("%+v\n", employee)
}
在上面的代码中,我们需要手动将User
类型转换为Employee
类型,因为它们的字段名和类型不完全相同。我们只复制了User
中的ID
和Name
字段,而HireDate
则是在Employee
结构体中新增的字段。
总之,需要根据具体情况进行结构体转换,特别是在字段名和类型不完全相同的情况下需要手动转换。
欢迎关注公众号上海php自学中心,一起交流。
推荐文章: