Go 指標介紹

數值指標

package main

import "fmt"

func main() {
    var creature string = "shark"
    var pointer *string = &creature

    fmt.Println("creature =", creature)     // creature = shark
    fmt.Println("pointer =", pointer)       // pointer = 0xc0000721e0
    fmt.Println("*pointer =", *pointer)     // *pointer = shark

    // 重新設定指標值
    *pointer = "jellyfish"
    fmt.Println("*pointer =", *pointer)     // *pointer = jellyfish
    fmt.Println("creature =", creature)     // 因為 pointer 是指到 creature 所以 creature 值會跟著變  creature = jellyfish
}  

函數指標

package main

import "fmt"

type Creature struct {
    Species string
}

func main() {
    var creature Creature = Creature{Species: "shark"}

    fmt.Printf("1) %+v\n", creature)     // 1) {Species:shark}
    changeCreature(creature)             // 2) {Species:jellyfish}
    changeCreatureA(&creature)             // 2) &{Species:jellyfish}
    fmt.Printf("3) %+v\n", creature)     // 3) {Species:shark}
}

func changeCreature(creature Creature) {
    creature.Species = "jellyfish"
    fmt.Printf("2) %+v\n", creature)
}

func changeCreatureA(creature *Creature) {
    creature.Species = "jellyfish"
    fmt.Printf("2) %+v\n", creature)
}

nil 指標

package main

import "fmt"

type Creature struct {
    Species string
}

func main() {
    var creature *Creature

    fmt.Printf("1) %+v\n", creature)    // 1) <nil>
    changeCreature(creature)            // creature is nil
    fmt.Printf("3) %+v\n", creature)    // 3) <nil>
}

func changeCreature(creature *Creature) {
    if creature == nil {
        fmt.Println("creature is nil")   // creature is nil
        return
    }

    creature.Species = "jellyfish"
    fmt.Printf("2) %+v\n", creature)
}

範例二

package main

import "fmt"

type Creature struct {
    Species string
}

func (c *Creature) Reset() {
    c.Species = ""
}

func main() {
    var creature Creature = Creature{Species: "shark"}

    fmt.Printf("1) %+v\n", creature)   // 1) {Species:shark}
    creature.Reset()
    fmt.Printf("2) %+v\n", creature)   // 2) {Species:}
}