Home > Article > Backend Development > Explore the conversion of structure to interface in golang
There are two methods for structure to interface conversion: embedding the structure or using the adapter pattern. Embedding is a more direct approach that creates a new type with the fields of the structure and the methods of the interface. The Adapter pattern uses an intermediate type that contains instances of the structure and implements the interface. The converted interface only contains interface methods and does not contain other fields of the structure. Both methods can be used to achieve reusability of object-oriented code and provide flexibility in using different interfaces in the system.
Conversion from structure to interface in Go language
What are structures and interfaces?
Conversion from structure to interface
1. Embedding
The simplest way is to embed the structure embedded into the interface. This creates a new type that has both the fields of the structure and the methods of the interface.
type Person struct { Name string Age int } type Personer interface { GetName() string } // 嵌入 Person 到 Personer 4 type EmbeddedPerson struct { Person } func (p EmbeddedPerson) GetName() string { return p.Name }
2. Adapter pattern
Another method is to use the adapter pattern to create a new type that contains an instance of the structure and implements the interface.
type Personer interface { GetName() string } type Person struct { Name string Age int } // PersonAdapter 适配器 type PersonAdapter struct { p *Person } func (a *PersonAdapter) GetName() string { return a.p.Name } func main() { p := Person{"John", 30} pa := &PersonAdapter{&p} fmt.Println(pa.GetName()) // 输出:John }
Note:
Practical case
Suppose we have a User
structure that contains name and email. We are going to create an interface Userer
so that we can look up users based on their name or email.
Use embedding:
type User struct { Name string Email string } type Userer interface { GetName() string GetEmail() string } type EmbeddedUser struct { User } func (u EmbeddedUser) GetName() string { return u.Name } func (u EmbeddedUser) GetEmail() string { return u.Email }
Use adapter mode:
type Userer interface { GetName() string GetEmail() string } type User struct { Name string Email string } type UserAdapter struct { user *User } func (ua *UserAdapter) GetName() string { return ua.user.Name } func (ua *UserAdapter) GetEmail() string { return ua.user.Email } func main() { user := User{"John", "john@example.com"} userAdapter := &UserAdapter{&user} fmt.Println(userAdapter.GetName()) // 输出:John fmt.Println(userAdapter.GetEmail()) // 输出:john@example.com }
The above is the detailed content of Explore the conversion of structure to interface in golang. For more information, please follow other related articles on the PHP Chinese website!