I am doing the http://tour.golang.org/. Could anyone explain me lines 1,3,5 and 7 this function especially what \'*\' and \'&\' do? I mean by mentioning the
Your question doesn't match very well the example given but I'll try to be straightforward.
Let's suppose we have a variable named a
which holds the integer 5 and another variable named p
which is going to be a pointer.
This is where the *
and &
come into the game.
Printing variables with them can generate different output, so it all depends on the situation and how well you use.
The use of *
and &
can save you lines of code (that doesn't really matter in small projects) and make your code more beautiful/readable.
&
returns the memory address of the following variable.
*
returns the value of the following variable (which should hold the memory address of a variable, unless you want to get weird output and possibly problems because you're accessing your computer's RAM)
var a = 5
var p = &a // p holds variable a's memory address
fmt.Printf("Address of var a: %p\n", p)
fmt.Printf("Value of var a: %v\n", *p)
// Let's change a value (using the initial variable or the pointer)
*p = 3 // using pointer
a = 3 // using initial var
fmt.Printf("Address of var a: %p\n", p)
fmt.Printf("Value of var a: %v\n", *p)
All in all, when using * and & in remember that * is for setting the value of the variable you're pointing to and & is the address of the variable you're pointing to/want to point to.
Hope this answer helps.