My object is not updated even if I use the pointer to a type to update it

后端 未结 3 1557
我在风中等你
我在风中等你 2020-11-29 11:38

I store some Individual objects in a slice. Before appending it to the slice I print the name of the Individual object.

After I have stored

3条回答
  •  温柔的废话
    2020-11-29 12:27

    Two things to fix this:

    • You need the methods attach via a "pointer" method, otherwise the name is only changed inside the method.
    • You need to use pointers for the actual Person variables, since they need to implement an interface
    type Individual interface {
        GetName() *string
        SetName(name string)
    }
    
    type Person struct {
        name string
    }
    
    // Implement functions of the Individual interface
    func (p Person) GetName() *string  {
        return &p.name
    }
    
    func (p *Person) SetName(newName string)  {
        p.name = newName
    }
    
    
    var individuals []Individual
    
    func main() {
        person := &Person{name: "Steve"}
        fmt.Println(person)
    
        individuals = append(individuals, person) // append Person to slice
        p1 := individuals[0]     // Retrieve the only Person from slice
        p1.SetName("Peter")      // Change name
        fmt.Println(p1)          // Prints "Steve"
        fmt.Println(person)      // Prints "Steve"
    }
    

    Example on Go Playground.

提交回复
热议问题