the difference between type and type address in struct

107 views
Skip to first unread message

Mandel

unread,
Aug 28, 2022, 6:56:30 AM8/28/22
to golang-nuts
the difference between type  and  type address in struct
type dog struct {
 age int 
 name string
type A struct {
     d *dog
}
type B struct {
     d dog
}
the difference between struct A and struct B.

jake...@gmail.com

unread,
Aug 28, 2022, 9:26:13 AM8/28/22
to golang-nuts
The terminology we would generally use is '*dog' is a pointer, not a "type address".

The difference really has nothing to do with structs, but is the difference between a value and a pointer to a value. If you understand pointers in general, then this more complicated case will make sense. I suggest searching "pointers in go explained", which will give you a number of tutorials that explain pointers.

In this case, the biggest difference is that each instance of B will always contain its own 'dog' value, but instances of A may share a 'dog' value, if d points to the same 'dog' value. Seehttps://go.dev/play/p/NlSsMc8b7To for a demonstration.

Brian Candler

unread,
Aug 28, 2022, 11:18:44 AM8/28/22
to golang-nuts
Another difference is that the *dog value in type A may be nil, meaning "no dog" - indeed, this is the default (zero) value of a pointer.

Attempting to follow (deference) such a nil pointer, in other words trying to access the dog value that it points to, will result in a panic.

Reply all
Reply to author
Forward
0 new messages