Pointer questions

I am a newbie and I have a couple of questions. I have some questions about this code snipplet.

package main

type Dummy struct {
	Name  *string `json:"name"`
	Image *string `json:"image"`
}

func dummyFunc() Dummy {
	row := database.DbConn.QueryRow("SELECT name, image FROM mytable WHERE id=5")

	var dummy Dummy
	row.Scan(&dummy.Name, &dummy.Image)

	return dummy
}

I ran this code and to my surprise the values are able to set in dummy.Name and dummy.Image but I don’t understand how. I double checked in the debugger that Name and Image are nil. Hope someone can explain this to me. Another question is that what does it mean when an & is put in front of a pointer type? is that like an address of an address? How’s that possible? I am a little confused. Thanks very much.

Name *string means that Name is a pointer type that points to the location of a string

&dummy.Name means a pointer to the var dummy that is a “interface type” of Dummy.

And interface type contains a pointer type and a value type.

You are correct that if you did &var to a var *string that would be a pointer to a pointer but you are doing a pointer to a value type that contains pointers.

There is some magic that Go and some libraries do in certain cased that automagically dereferences pointers implicitly, it still confuses me sometimes. But luckily JetBrains GoLand usually suggested the correct fix to make it all work when I am trying to use someone else’s code that mixes pointer and value types.

1 Like

Thanks Jarrod. That makes sense.