简体   繁体   中英

What's the difference between these functions in golang?

I'm new to Go programming and wondering what's the difference (if any) there between

a.

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

b.

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

If you are actually asking what the difference of those b 's are, one is a pointer to the object passed as an argument to DoSomething , and the other is a pointer to a copy of the object passed as an argument to DoSomething .

https://play.golang.org/p/ush0hDZsdE

type A struct {
    f string
}

func DoSomethingPtr(a *A) {
    b := a
    b.f = "hi"
}

func DoSomething(a A) {
    b := &a
    b.f = "hey"
}

func main() {
    x := A{"hello"}
    DoSomething(x)
    fmt.Println(x)
    DoSomethingPtr(&x)
    fmt.Println(x)
}

In general, these two functions will assign different values to b . The second one makes a copy of the argument, and so the a inside the function generally has a different memory address than whatever input is passed into the function. See this playground example

package main

type A struct{
    x int
}
var b *A

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

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

func main() {
    var a = A{3}
    println(&a)
    d(&a)
    println(b)
    e(a)
    println(b)
}

Interestingly, if you make the type A an empty struct instead, and initialize var a = A{} , you actually see the same value for b in the println statements.

That's because for the empty-struct type, there can only really only ever be 1 value, and its immutable, so all instances of it share the same memory address?

The variable b would be assigned a different value in each function. The values are different because one is passing a copied value and the other is passing a pointer to the original value in memory.

package main

import "fmt"

type A string

func DoSomethingPtr(a *A) {
    fmt.Println(a)
}

func DoSomething(a A) {
    fmt.Println(&a)
}

func main() {
    x := A("hello")
    DoSomething(x)
    DoSomethingPtr(&x)
}

Here is the executable proof.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM