Consider:
package main
import (
"fmt"
)
type Endpoint struct {
NeedsAuthentication bool
Uri string
}
type RefreshEndpoint struct {
Endpoint
Payload RefreshPayload
}
type RefreshPayload struct {
RefreshToken string
}
func main() {
refreshEndpoint := RefreshEndpoint{Endpoint: Endpoint{NeedsAuthentication: true, Uri: "/foo"}, Payload: RefreshPayload{RefreshToken: "xxx"}}
fmt.Printf("The uri is: %s, the access token is: %s", refreshEndpoint.Endpoint.Uri, refreshEndpoint.Payload.RefreshToken)
}
How can I compose these structs such that I don’t have to access Uri with refreshEndpoint.Endpoint.Uri? Is there a way to access Uri like refreshEndpoints.Uri without creating a method that hides the "extra" Endpoint namespace?
>Solution :
Endpoint is already embedded, so you can access Uri already:
fmt.Printf("The uri is: %s, the access token is: %s", refreshEndpoint.Uri, refreshEndpoint.Payload.RefreshToken)
You still need to use the full namespace when you declare a literal:
refreshEndpoint := RefreshEndpoint{Endpoint: Endpoint{NeedsAuthentication: true, Uri: "/foo"}, Payload: RefreshPayload{RefreshToken: "xxx"}}
However, you can do:
refreshEndpoint := RefreshEndpoint{Payload: RefreshPayload{RefreshToken: "xxx"}}
refreshEndpoint.Uri="/foo"
refreshEndpoint.NeedsAuthentication=true