In Go, interfaces are typically used to define functionality rather than data. This means that while you can specify methods in an interface, you cannot specify any required fields in the implementations.
However, using embedded structs, it's possible to create interfaces that effectively define data by exposing it through methods.
Consider the following example:
type PersonProvider interface { GetPerson() *Person } type Person struct { Name string Age int64 } func (p *Person) GetPerson() *Person { return p } type Bob struct { FavoriteNumber int64 Person }
In this example, the PersonProvider interface defines a method that returns a pointer to a Person object. The Person struct contains the data fields Name and Age. The Bob struct embeds the Person struct, effectively inheriting its fields.
Functions can interact with the embedded data through the GetPerson() method:
func SayHi(pp PersonProvider) { fmt.Printf("Hello, %v!\r", pp.GetPerson().Name) } func main() { b := &Bob{ 5, Person{"Bob", 23}, } SayHi(b) fmt.Printf("You're %v years old now!", b.Age) }
This technique allows for interfaces that define data rather than behavior. It provides increased flexibility by allowing structs to implement interfaces without exposing their concrete fields. However, it's important to note that exposing pointers still grants direct access to the data, offering limited additional flexibility.
Additionally, Go conventions do not always require the use of abstractions for data access. In many cases, exposing data attributes through embedding or public fields is acceptable. When considering this technique, it's recommended to assess on a case-by-case basis whether it provides significant benefits over exposing attributes directly. If exposing data through getters and setters is not crucial for future flexibility or API compatibility, public attributes may be a simpler solution.
Overall, while the technique presented is a clever trick, it's advisable to weigh the need for it carefully and consider alternative approaches that might be more appropriate in some contexts.
The above is the detailed content of Should You Use Embedded Structs to Define Data in Go Interfaces?. For more information, please follow other related articles on the PHP Chinese website!