access to struct field from struct method field

Issue

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()
}

Solution

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.

Answered By – icza

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.