Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the address of struct variable in go

I am new to go I want to print the address of struct variable in go here is my program

type Rect struct {
 width int
 name int 
}

func main() {
 r := Rect{4,6}
 p := &r
 p.width = 15

fmt.Println("-----",&p,r,p,&r)

}

output of this

  _____0x40c130 {15 6} &{15 6} &{15 6}

but i want to print the address of r variable as i know that '&' represents the address and '*' points the value of pointer location but here i am unable to print the address of r, I am using online editor of go-lang https://play.golang.org/

As well I want to store this address in some variable.

like image 968
Kiwi Rupela Avatar asked May 13 '19 12:05

Kiwi Rupela


People also ask

How do I print a struct address?

In C, we can get the memory address of any variable or member field (of struct). To do so, we use the address of (&) operator, the %p specifier to print it and a casting of (void*) on the address.

How do I print a struct with fields in Go?

Printf with #v includes main. Fields that is the structure's name. It includes “main” to distinguish the structure present in different packages. Second possible way is to use function Marshal of package encoding/json.


1 Answers

When you print values using fmt.Println(), the default format will be used. Quoting from package doc of fmt:

The default format for %v is:

bool:                    %t
int, int8 etc.:          %d
uint, uint8 etc.:        %d, %#x if printed with %#v
float32, complex64, etc: %g
string:                  %s
chan:                    %p
pointer:                 %p

For compound objects, the elements are printed using these rules, recursively, laid out like this:

struct:             {field0 field1 ...}
array, slice:       [elem0 elem1 ...]
maps:               map[key1:value1 key2:value2 ...]
pointer to above:   &{}, &[], &map[]

The address of a struct value is the last line, so it is treated special and thus printed using the &{} syntax.

If you want to print its address, don't use the default format, but use a format string and specify you want the address (pointer) explicitly with the %p verb:

fmt.Printf("%p\n", &r)

This will output (try it on the Go Playground):

0x414020
like image 162
icza Avatar answered Oct 18 '22 20:10

icza