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 *.
In Go, := is for declaration + assignment, whereas = is for assignment only. For example, var foo int = 10 is the same as foo := 10 .
:= represents a variable, we can assign a value to a variable using :=.
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++.
= 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With