Go指針實例

在這個實例中,將展示如何使用指針,並使用2相對應的函數:zerovalzeroptrzeroval()函數有一個int參數,因此參數將通過值傳遞給它。 zeroval將獲得ival的拷貝,它與調用函數中的值有所不同。

相反,zeroptr有一個* int參數,這意味着它需要一個int指針。函數體中的* iptr代碼將指針從存儲器地址解引用到該地址處的當前值。將值分配給取消引用的指針會更改引用地址處的值。

&i語法獲取了i變量的存儲器地址,即指向i的指針。指針也可以打印。

main函數中zeroval不會改變i的值,但zeroptr會。是因爲它有一個對該變量的內存地址的引用。

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考:http://www.yiibai.com/go/go\_environment.html

pointers.go的完整代碼如下所示 -

package main

import "fmt"

// We'll show how pointers work in contrast to values with
// 2 functions: `zeroval` and `zeroptr`. `zeroval` has an
// `int` parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
func zeroval(ival int) {
    ival = 0
}

// `zeroptr` in contrast has an `*int` parameter, meaning
// that it takes an `int` pointer. The `*iptr` code in the
// function body then _dereferences_ the pointer from its
// memory address to the current value at that address.
// Assigning a value to a dereferenced pointer changes the
// value at the referenced address.
func zeroptr(iptr *int) {
    *iptr = 0
}

func main() {
    i := 1
    fmt.Println("initial:", i)

    zeroval(i)
    fmt.Println("zeroval:", i)

    // The `&i` syntax gives the memory address of `i`,
    // i.e. a pointer to `i`.
    zeroptr(&i)
    fmt.Println("zeroptr:", i)

    // Pointers can be printed too.
    fmt.Println("pointer:", &i)
}

執行上面代碼,將得到以下輸出結果 -

F:\worksp\golang>go run pointers.go
initial: 1
zeroval: 1
zeroptr: 0
pointer: 0xc04203c1c0