How to set and get fields in struct's method

后端 未结 3 863
故里飘歌
故里飘歌 2020-11-27 03:02

After creating a struct like this:

type Foo struct {
    name string
}

func (f Foo) SetName(name string) {
    f.name = name
}

func (f Foo) GetName() strin         


        
3条回答
  •  萌比男神i
    2020-11-27 03:16

    Commentary (and working) example:

    package main
    
    import "fmt"
    
    type Foo struct {
        name string
    }
    
    // SetName receives a pointer to Foo so it can modify it.
    func (f *Foo) SetName(name string) {
        f.name = name
    }
    
    // Name receives a copy of Foo since it doesn't need to modify it.
    func (f Foo) Name() string {
        return f.name
    }
    
    func main() {
        // Notice the Foo{}. The new(Foo) was just a syntactic sugar for &Foo{}
        // and we don't need a pointer to the Foo, so I replaced it.
        // Not relevant to the problem, though.
        p := Foo{}
        p.SetName("Abc")
        name := p.Name()
        fmt.Println(name)
    }
    

    Test it and take A Tour of Go to learn more about methods and pointers, and the basics of Go at all.

提交回复
热议问题