In golang, what is the difference between & and *

Can someone explain the difference between and and * in GO lang .. and give examples of when and and * will be used to illustrate the difference? From what I read, they both relate to accessing a variable's memory cell, but I'm not sure when to use / /.

+4
source share
5 answers

Here is a very simple example illustrating the use of &and *. Note that it *can be used for two different things: 1) declare a variable as a pointer 2) to dereference a pointer.

package main

import "fmt"

func main() {
    b := 6 

    var b_ptr *int // *int is used delcare variable
                   // b_ptr to be a pointer to an int

    b_ptr = &b     // b_ptr is assigned value that is the address
                       // of where variable b is stored

    // Shorhand for the above two lines is:
    // b_ptr := &b

    fmt.Printf("address of b_ptr: %p\n", b_ptr)

    // We can use *b_ptr get the value that is stored
    // at address b_ptr, or dereference 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
+6
source

. " " :

x T &x *T x. [& Hellip;]

x *T - *x T, x. x - nil, *x .

: & ( ) , , * , ( nil, , -).

+5

& - . * , " ".

, p := &SometType{}, , SomeType{}, , , p. p *SomeType, , . * , .

deference, , C ++. , . , p *SomeType, SomeType, someType := *p, .

, . , - .

+2

& .

* "" , , .

For types var *type, it means that "* var has a type of type" (and without a variable, it simply means "a pointer to something of type".

+1
source

& and * is mainly used 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
}
-3
source

Source: https://habr.com/ru/post/1612477/


All Articles