Pointer 變數: 指標
Golang 基礎: Pointer 變數 指標
Categories:
類型 | 說明 |
---|---|
&variable | 會回傳該變數 value 的 address,表示給我這個變數值的「記憶體位置」 |
*pointer | 會回傳該 address 的 value,表示給我這個記憶體位置指稱到的「值」 |
package main
import "fmt"
func changeNameByValue(name_value string) {
name_value = `KJ`
}
func changeNameByPointer(name_pointer *string) {
*name_pointer = `KJ`
}
func main() {
name := `Nobody`
fmt.Println("initial Name:", name)
// call by value
changeNameByValue(name)
fmt.Println("after changeNameByValue:", name)
// call by reference
changeNameByPointer(&name)
fmt.Println("after changeNameByPointer:", name)
fmt.Println("Name pointer:", &name)
}
// initial Name: Nobody
// after changeNameByValue: Nobody
// after changeNameByPointer: KJ
// Name pointer: 0xc000010240