这些功能之间的区别是什么



以下函数之间有什么区别?

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

第一个函数接收指向类型为A的值的指针。第二个接收类型A的值的副本。以下是您如何调用第一个函数:

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

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

这里调用第二个函数:

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

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

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
}

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

相关内容

最新更新