This is the 17th day of my participation in the August Text Challenge.More challenges in August

1.1 Concept of Pointers

A pointer is a variable that stores the memory address of another variable.

As we all know, variables are handy placeholders for referencing computer memory addresses.

A pointer variable can point to the memory address of any value and it points to the memory address of that value.

In the figure above, variable B has a value of 156 and is stored at memory address 0x1040a124. Variable A holds the address of B, and now A is thought to point to B.

#1.2 Obtaining the address of a variable

The Go address is &, and when used before a variable, it returns the memory address of the variable.

Package main import "FMT" func main() {var a int = 10 FMT.Printf(" variable address: %x\n", &a)}Copy the code

Running results:

Variable address: 20818A220Copy the code

Declare a pointer. *T is the type of a pointer variable that points to a value of type T.

var var_name *var-type
Copy the code

Var-type is the type of a pointer, var_name is the name of a pointer variable, and * is used to specify whether the variable is a pointer.

Var IP *int /* points to an integer */ var fp *float32 /* Points to a floating point */Copy the code

Sample code:

Package main import "FMT" func main() {var a int= 20 /* Declare actual variables */ var IP *int /* declare pointer variables */ IP = &a /* Store address of pointer variables */ FMT.Printf("a variable's address is: %x\n", &a) /* Pointer variable's storage address */ FMT.Printf(" IP variable's storage address: %x\n", &a) X % \ n ", IP) / * use pointer to access values * / FMT Printf (" * value of the variable IP: % d \ n ", * IP)}Copy the code

Running results:

The address of variable A is: 20818a220 The storage address of variable IP is: 20818a220 * the value of variable IP is: 20Copy the code

Sample code:

package main

import "fmt"

type name int8
type first struct {
    a int
    b bool
    name
}

func main() {
    a := new(first)
    a.a = 1
    a.name = 11
    fmt.Println(a.b, a.a, a.name)
}
Copy the code

Running results:

false 1 11
Copy the code

Uninitialized variables are automatically assigned initial values

package main

import "fmt"

type name int8
type first struct {
    a int
    b bool
    name
}

func main() {
    var a = first{1, false, 2}
    var b *first = &a
    fmt.Println(a.b, a.a, a.name, &a, b.a, &b, (*b).a)
}
Copy the code

Running results:

false 1 2 &{1 false 2} 1 0xc042068018 1
Copy the code

Gets the address of a pointer and prefixes a pointer variable with an ampersand

#Null pointer

Go null pointer

When a pointer is defined without assigning any variables, its value is nil. Nil Pointers are also called null Pointers. Nil is conceptually the same as null, None, nil, and null in other languages. A pointer variable is usually abbreviated to PTR.

Null pointer judgment:

if(ptr ! = nil) /* PTR not null */ if(PTR == nil) /* PTR is null */Copy the code