In Go language, assertions can be used to complete interface conversion and structure conversion. Interface conversion includes type assertions and value assertions, which are used to convert values from one interface type to another interface type. Structure conversion is used to convert one structure into another structure.
Use assertions in Go to implement conversion of interfaces and structures
The interface in Go is a collection of methods that allow Different underlying types of values implement them. Interface conversion allows you to convert a value from one interface type to another interface type.
A structure is a collection of related data fields. Sometimes you may want to convert one structure into another. This can be done using assertions.
Interface Conversion
To convert a value from one interface type to another, you can use assertions. Assertions come in two forms:
The following example demonstrates how to use type assertions:
package main import "fmt" type Animal interface { Speak() string } type Dog struct {} func (d Dog) Speak() string { return "Woof!" } type Cat struct {} func (c Cat) Speak() string { return "Meow!"} func main() { var animals []Animal animals = append(animals, Dog{}, Cat{}) for _, animal := range animals { if dog, ok := animal.(Dog); ok { fmt.Println("Dog says:", dog.Speak()) } else if cat, ok := animal.(Cat); ok { fmt.Println("Cat says:", cat.Speak()) } } }
Structure conversion
To convert one structure to another, you can Use assertions. The following example demonstrates how to use assertions:
package main import "fmt" type User struct { Name string } type Employee struct { User Salary int } func main() { user := User{"Alice"} employee := Employee{User{"Bob"}, 1000} // 使用断言将 User 转换为 Employee if employee, ok := user.(Employee); ok { fmt.Println("Employee:", employee.Name, employee.Salary) } // 使用断言将 Employee 转换为 User if user, ok := employee.User.(User); ok { fmt.Println("User:", user.Name) } }
The above is the detailed content of Use golang to convert interfaces and structures. For more information, please follow other related articles on the PHP Chinese website!