1
votes

I have the following piece of code working correctly:

type Type struct {
    p string
}

func foo() {
    t := Type { p: "hola" }
    bar(&t)
}

var bar = func(t *Type) {
    t.p = "chau"
}

func Test1() {
    var baz *Type
    bar = func(t *Type) {
        baz = t
    }
    foo()
    fmt.Println(baz.p)
}

Basically I'm mocking the bar function in order to know the parameter that the function foo is passing when it runs. Now, suppose that I want to extract the logic of the mocking function in another function, how should I do it? I tried the following but got an invalid memory address or nil pointer dereference:

func mockedBar(b** Type) func(*Type) {
    return func(t *Type) {
        *b = t
    }
}

func Test2() {
    var baz **Type
    bar = mockedBar(baz)
    foo()
    fmt.Println((**baz).p)
}
2

2 Answers

0
votes

Use this:

var baz *Type
bar = mockedBar(&baz)
foo()
fmt.Println((*baz).p)

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

0
votes

var means that you will allocate the following variable with the given type.

var t Type will allocate the full size of Type, 24 bytes, for example.

var p *Type will allocate only 4-8 bytes for the Pointer itself.

var pp **Type will allocate the same 4-8 bytes because it's the same pointer but which points to another pointer.

To solve that puzzle you have to:

// allocate an object and take a pointer to it
p := &Type{}
/*
it's also equivalent of:

var t Type
p := &t 
*/

// take a pointer to pointer
pp := &p