Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In golang, what is the difference between & and *

Tags:

go

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 *.

like image 433
tyonne Avatar asked Oct 20 '15 17:10

tyonne


People also ask

What is the difference between and := in golang?

In Go, := is for declaration + assignment, whereas = is for assignment only. For example, var foo int = 10 is the same as foo := 10 .

What does := mean in golang?

:= represents a variable, we can assign a value to a variable using :=.

What does * and & indicate in golang?

Write a proper example, ideally which can be run on golang.org. But in any case, Go pointers are pretty much the same as in C++. You get a pointer with & and dereference it with * . * is also used to declare pointer type. Just like in C++.

What is the difference between and :=?

= operator assigns a value either as a part of the SET statement or as a part of the SET clause in an UPDATE statement, in any other case = operator is interpreted as a comparison operator. On the other hand, := operator assigns a value and it is never interpreted as a comparison operator.


1 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 
like image 173
Akavall Avatar answered Sep 17 '22 12:09

Akavall