Functional Interfaces in Go
Go interfaces are primarily used to define functionality rather than data. While you can define methods in an interface, you cannot specify required fields. However, there are ways to work around this limitation and create interfaces that model data.
Emulating Data Interfaces with Embedded Structs
One approach is to use embedded structs. Consider the example where you want to define a Person interface with Name and Age fields:
type PersonProvider interface { GetPerson() *Person } type Person struct { Name string Age int64 }
Now, structs implementing PersonProvider can embed Person and expose its fields through the GetPerson method.
type Bob struct { FavoriteNumber int64 Person }
This technique provides a means to expose data through an interface, while ensuring compile-time type safety. However, it's important to note that it still exposes pointers, allowing direct access to data.
The Case for Exposing Data Attributes
While the emulation technique is valid, it raises the question of whether it's the best approach. Go conventions do not strictly mandate the use of abstractions for data access. It's sometimes simpler and more efficient to expose public data attributes, especially when direct access is required.
However, if data exposure could potentially complicate future changes, it's wise to consider using methods for property access and modifications. This offers more flexibility for evolving the underlying data structure while maintaining API compatibility.
The Benefits of Getters and Setters
Hiding properties behind getters and setters provides several advantages.
Considerations and Caveats
The above is the detailed content of Should Go Interfaces Expose Data Directly or Through Getters and Setters?. For more information, please follow other related articles on the PHP Chinese website!