无法在golang中通过引用修改对象

Cannot modify object by reference in golang

为什么我不能在 golang 中通过引用传递对象?我 99% 确定我是通过引用函数而不是复制对象来传递对象。我是新手,我总是喜欢在创建真正的代码之前做这样的练习

无论如何我的问题是为什么最后一行打印 Doggy? 我期待最后一行打印 name of dog after: changed name!

代码

package main

import "fmt"

// base type
type Animal struct {
    Name string
    Age  int
}

type Dog struct {
    Animal
    PropertyFoo1 int // some field specific to a dog
}

func modifyAnimalName(animal *Animal) {
    (*animal).Name = "changed name!"
}

func main() {

    // create a new dog
    dog := Dog{
        Animal: Animal{
            Name: "Doggy",
            Age:  5,
        },
    }

    var animal Animal = dog.Animal

    // before and after values when calling modifyAnimalName(&animal)
    fmt.Printf("name of dog before: %s \n", dog.Name)
    modifyAnimalName(&animal) // modify animal name
    // why does this prints Doggy?!
    fmt.Printf("name of dog after: %s \n", dog.Name)
}


控制台输出:

name of dog before: Doggy 
name of dog after: Doggy

编辑

抱歉问了这个愚蠢的问题,我才刚开始学围棋

@tkausl 谢谢。由于您的评论,我刚刚注意到这一行正在复制一个实体对象。

var animal Animal = dog.Animal

因此我将代码修改为:

    var animal *Animal = &dog.Animal

    fmt.Printf("name of dog before: %s \n", dog.Name)
    modifyAnimalName(animal)
    // now it prints a different name :)
    fmt.Printf("name of dog after: %s \n", dog.Name)

您没有通过引用传递。这里有两个解决问题的办法。

解决方案 1:使用正则函数

package main

import "fmt"

// base type
type Animal struct {
    Name string
    Age  int
}

type Dog struct {
    Animal
    PropertyFoo1 int // some field specific to a dog
}

func modifyAnimalName(animal *Animal) {
    animal.Name = "changed name!"
}

func main() {
    // create a new dog
    dog := Dog{
        Animal: Animal{
            Name: "Doggy",
            Age:  5,
        },
    }

    var animal *Animal = &dog.Animal
    fmt.Printf("name of dog before: %s \n", dog.Name)
    modifyAnimalName(animal) // modify animal name
    fmt.Printf("name of dog after: %s \n", dog.Name)
}

方案二:使用方法

package main

import "fmt"

type Animal struct {
    Name string
    Age  int
}

type Dog struct {
    Animal
    PropertyFoo1 int // some field specific to a dog
}

func (a *Animal) modifyAnimalName() {
    a.Name = "changed name!"
}

func main() {
    // create a new dog
    dog := Dog{
        Animal: Animal{
            Name: "Doggy",
            Age:  5,
        },
    }
    var animal *Animal = &dog.Animal
    fmt.Printf("name of dog before: %s \n", dog.Name)
    animal.modifyAnimalName()
    fmt.Printf("name of dog after: %s \n", dog.Name)
}