Go Interface Fields: A Study in Data Access
Go interfaces are known for defining functionality rather than data. While one can specify methods in an interface, fields cannot be declared directly.
type Giver interface { Give() int64 }
This behavior raises the question of whether it is possible to define an interface that represents data. While not directly possible, there is a workaround that involves embedded structs and the GetPerson() method.
type PersonProvider interface { GetPerson() *Person } type Person struct { Name string Age int64 } type Bob struct { FavoriteNumber int64 Person }
By defining an interface that specifies a GetPerson() method, one can effectively expose data to functions that are designed to use that interface.
func DoBirthday(pp PersonProvider) { pers := pp.GetPerson() pers.Age += 1 }
However, it is crucial to note that this method does not eliminate direct access to data. It only provides an abstraction layer that can be utilized for specific purposes.
Pros and Cons: A Balanced Perspective
While this workaround can be a useful technique, it is essential to weigh its pros and cons carefully.
Pros:
Cons:
Ultimately, the decision of whether or not to use this technique depends on the specific use case and the potential for future changes. If it is highly likely that exposure of the data could complicate future implementation, using getter/setter methods becomes more compelling.
However, if the interface is only used within a single project and the data remains relatively stable, it may be simpler and more efficient to expose the data directly without an abstraction layer.
The above is the detailed content of Can Go Interfaces Effectively Represent Data?. For more information, please follow other related articles on the PHP Chinese website!