这些功能之间有什么区别?

时间:2020-05-02 09:06:24

标签: go

以下功能之间有什么区别?

func DoSomething(a *A){
    b = a
}

func DoSomething(a A){
    b = &a
}

2 个答案:

答案 0 :(得分:1)

第一个函数接收pointer到类型A的值。第二个接收类型A的值的副本。这是第一个函数的调用方式:

a := A{...}
DoSomething(&a)

在这种情况下,DoSomething接收到指向原始对象的指针并可以对其进行修改。

这是第二个函数的调用:

a := A{...}
DoSomething(a)

在这种情况下,DoSomething收到a的副本,因此它不能修改原始对象(但是如果原始对象包含指向其他结构的指针,则可以对其进行修改)

答案 1 :(得分:0)

func DoSomething(a *A) { // a is a pointer to given argument of type A
    b = a // b is a copy of a, which is also the same pointer

    // this is useful to change the given object directly
}

func DoSomething(a A) { // a is a copy of the given object type A
    b = &a // b is the pointer of a
}

请记住,指针是保存内存地址的变量。