Composition and embedding
suggest changeComposition provides an alternative to inheritance. A struct may include another type by name in its declaration:
type Request struct {
Resource string
}
type AuthenticatedRequest struct {
Request
Username, Password string
}
In the example above, AuthenticatedRequest will contain four public members: Resource, Request, Username, and Password.
Composite structs can be instantiated and used the same way as normal structs:
func main() {
ar := new(AuthenticatedRequest)
ar.Resource = "example.com/request"
ar.Username = "bob"
ar.Password = "P@ssw0rd"
fmt.Printf("%#v", ar)
}
Embedding
In the previous example, Request is an embedded field. You can also embed another type to add behavior. Continuing the example, suppose we want helpers that prefix Resource with http:// or https://. One option is to put the methods on AuthenticatedRequest. Another is to embed a type that already has them:
type ResourceFormatter struct {}
func (r *ResourceFormatter) FormatHTTP(resource string) string {
return fmt.Sprintf("http://%s", resource)
}
func (r *ResourceFormatter) FormatHTTPS(resource string) string {
return fmt.Sprintf("https://%s", resource)
}
type AuthenticatedRequest struct {
Request
Username, Password string
ResourceFormatter
}
And now the main function could do the following:
func main() {
ar := new(AuthenticatedRequest)
ar.Resource = "www.example.com/request"
ar.Username = "bob"
ar.Password = "P@ssw0rd"
println(ar.FormatHTTP(ar.Resource))
println(ar.FormatHTTPS(ar.Resource))
fmt.Printf("%#v", ar)
}
AuthenticatedRequest now has an embedded ResourceFormatter, so FormatHTTP and FormatHTTPS are promoted to it.
The methods on ResourceFormatter still cannot see the fields of AuthenticatedRequest. That is why FormatHTTP takes the resource string as an argument.