Home > Software design >  access to struct field from struct method field
access to struct field from struct method field

Time:04-17

How I can access struct field Name from struct method field PrintName example:

type Data struct {
    Name      string
    PrintName func()
}

func main() {
    data := Data{
        Name: "Name",
        PrintName: func() {
            fmt.Println(Name)
        },
    }

    data.PrintName()
}

CodePudding user response:

The function value you assign to Data.PrintName has no connection to the enclosing struct whatsoever, so in the general case it can't access the Name field.

If you want to access the name field, you have to pass it explicitly, or use a closure that can access the data struct like this:

data := Data{
    Name: "Name",
}

data.PrintName = func() {
    fmt.Println(data.Name)
}

data.PrintName()

This will output (try it on the Go Playground):

Name

In this example the function value we assign to data.PrintName field is a closure because it uses a variable from the enclosing block.

You can also choose to pass the Data value explicitly to the function value, but then its signature must be modified:

type Data struct {
    Name      string
    PrintName func(d Data)
}

func main() {
    data := Data{
        Name: "Name",
    }

    data.PrintName = func(d Data) {
        fmt.Println(d.Name)
    }

    data.PrintName(data)
}

This outputs the same, try this one on the Go Playground.

  • Related