Can someone explain the difference between &
and *
in GO lang and provide examples of when &
and *
would be used to illustrate the difference? From what I have read, they both relate to accessing a variables memory location however I'm not sure when to use &
or *
.
-
3It's hard to use the wrong one, since it usually won't compile. Just try them out to get a feel for what they do: tour.golang.org/moretypes/1– JimBOct 20, 2015 at 17:54
-
I second that advice. I couldn't accurately state the rules for the two operators like what's in the spec to save my life but I make them work whenever I need to through trial and error. Most of the time it won't compile if it's wrong because you'll have incompatible types on either side of an assignment.– evanmcdonnalOct 20, 2015 at 18:18
-
Does this answer your question? What does the asterisk do in "Go"?– Michael FreidgeimApr 2, 2021 at 5:26
7 Answers
Here is a very simple example, that illustrates how &
and *
are used. Note that *
can be used for two different things 1) to declare a variable to be a pointer 2) to dereference a pointer.
package main
import "fmt"
func main() {
b := 6
var b_ptr *int // *int is used to declare variable
// b_ptr to be a pointer to an int
b_ptr = &b // b_ptr is assigned the value that is the
// address of where variable b is stored
// Shorthand for the above two lines is:
// b_ptr := &b
fmt.Printf("address of b_ptr: %p\n", b_ptr)
// We can use *b_ptr to get the value that is stored
// at address b_ptr, known as dereferencing the pointer
fmt.Printf("value stored at b_ptr: %d\n", *b_ptr)
}
Result:
address of b_ptr: 0xc82007c1f0
value stored at b_ptr: 6
-
1In the context of " func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) ", why does Request dereference a pointer whereas ResponseWriter doesn't?– tyonneOct 26, 2015 at 1:05
-
That function signature usually looks like this
func(w http.ResponseWriter, r *http.Request)
, wherew
ishttp.ResponseWriter
object andr
is a pointer tohttp.Request
object. There is no dereferencing in this case.– AkavallOct 26, 2015 at 1:14 -
This is a good example, just use bPtr instead b_ptr as golang recommends avoid using "_" on variable declaration Aug 9, 2020 at 19:16
This helped me understand better, you can run the code in playground and play with it a bit to see how it behaves link here: https://play.golang.org/p/c7jxLJkdRDd (if link is deactivated in the future just copy paste the code below)
package main
import (
"fmt"
)
func main() {
var a = 5
var p = &a // copy by reference
var x = a // copy by value
fmt.Println("a = ", a) // a = 5
fmt.Println("p = ", p) // p = 0x10414020
fmt.Println("*p = ", *p) // *p = 5
fmt.Println("&p = ", &p) // &p = 0x1040c128
fmt.Println("x = ", x) // x = 5
fmt.Println("\n Change *p = 3")
*p = 3
fmt.Println("a = ", a) // a = 3
fmt.Println("p = ", p) // p = 0x10414020
fmt.Println("*p = ", *p) // *p = 3
fmt.Println("&p = ", &p) // &p = 0x1040c128
fmt.Println("x = ", x) // x = 5
fmt.Println("\n Change a = 888")
a = 888
fmt.Println("a = ", a) // a = 888
fmt.Println("p = ", p) // p = 0x10414020
fmt.Println("*p = ", *p) // *p = 888
fmt.Println("&p = ", &p) // &p = 0x1040c128
fmt.Println("x = ", x) // x = 5
fmt.Println("\n Change x = 1")
x = 1
fmt.Println("a = ", a) // a = 888
fmt.Println("p = ", p) // p = 0x10414020
fmt.Println("*p = ", *p) // *p = 888
fmt.Println("&p = ", &p) // &p = 0x1040c128
fmt.Println("x = ", x) // x = 1
&p = 3 // error: Cannot assign to &p because this is the address of variable a
}
They are the opposite. As explained in the "Address operators" section of the spec:
For an operand
x
of typeT
, the address operation&x
generates a pointer of type*T
tox
. […]For an operand
x
of pointer type*T
, the pointer indirection*x
denotes the variable of typeT
pointed to byx
. Ifx
isnil
, an attempt to evaluate*x
will cause a run-time panic.
In other words: &
takes a variable (or other addressable entity) and returns a pointer that points to it, whereas *
takes a pointer and returns the thing that it points to (unless it's nil
, meaning it doesn't point to anything).
-
Terminological correction: the
&
operation might take a value, not necessary a variable -- a good example is taking an address out of literal, like inv := &SomeType{}
; the*
operator returns a value, not a variable. A variable is the name; you can use it in a context which requires a value to refer to that value, but the pointer-dereferencing operator returns a value, and that value may have no variable bound to it.– kostixOct 20, 2015 at 18:39 -
@kostix: Good point, thanks; fixed. I'm too used to the Java spec, where any lvalue is called a "variable". :-P– ruakhOct 20, 2015 at 22:17
&
is the address of operator. *
represent a pointer in some cases, in others it is used as the 'dereference operator'.
So basically, if you do p := &SometType{}
the address of operator is used to return the address of the object created with the composite literal statement SomeType{}
if I were to remove it, I would no longer have a reference and instead be assigning the value directly to p
. In this case p
will be a *SomeType
because that is the types who's address I took. If I declare a type with *
in front of it, I'm designating it as a pointer to that type.
Now the last remaining use is as a the deference operator, you don't use this much in Go in my experience but it was super common in C and C++. This is used to return the actual value rather, it's most often leverage for assignment. Because like if I have p
and it is a *SomeType
and locally I want to assign to an instance of SomeType
then I'll need the following statement someType := *p
so that the value is assigned to my value type.
Hope that explanation helps. It's not the most technical one, rather my goal is to provide understanding of the common uses.
&
makes a pointer from a variable.
*
"fetches" the value stored where a pointer points to.
For types, var *type
means "*var is of the type type" (and without a variable, it simply means "a pointer to something of type".
b *int // creating variable
*b = 5 // assigning value
fmt.Println(*b) // getting value
-
2As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.– Community BotJun 27, 2022 at 15:37
& and * is used mainly in functions:
package main
import (
"fmt"
)
type Person struct {
name string
ageYears int
areDays int
}
func main() {
john := Person{name: "John", ageYears: 46}
toDays(&john)
fmt.Println(john) //{John 46 16790}
toDays2(john)
fmt.Println(john) //{John 46 16790}
}
func toDays(p *Person) {
p.areDays = p.ageYears * 365
}
func toDays2(p Person) {
p.areDays = -1
}