Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I directly access embedded struct fields in golang?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading