Go Playground在线运行 这里函数hello将局部变量i的指针作为函数返回值。在其他诸如C和C++之类的编程语言中这种写法是错误的,因为变量i是局部变量,一旦函数返回,局部变量就访问不到了。但是Golang会在局部变量初始化时检查下是否会在函数外部被引用,比如这里的局部变量i,其指针作为函数返回值返回出去,因此会在函数外部引用,这是Golang就将该局部变量分配在堆内存中。该程序执行结果为:
package main
import "fmt"
func main() {
a := 25
var b *int
if b == nil {
fmt.Println("b is", b)
b = &a
fmt.Println("b after initialization is", b)
}
}
b is <nil>
b after initialization is 0x414020
package main
import "fmt"
func main() {
size := new(int)
fmt.Printf("Size value is %d, type is %T, address is %v\n", *size, size, size)
*size = 85
fmt.Println("New size value is", *size)
}
Size value is 0, type is *int, address is 0x414020
New size value is 85
package main
import "fmt"
func main() {
b := 255
a := &b
fmt.Println("address of b is", a)
fmt.Println("value of b is", *a)
}
address of b is 0x414020
value of b is 255
package main
import "fmt"
func main() {
b := 255
a := &b
fmt.Println("address of b is", a)
fmt.Println("value of b is", *a)
*a++
fmt.Println("new value of b is", b)
}
address of b is 0x414020
value of b is 255
new value of b is 256
package main
import "fmt"
func change(p *int) {
*p = 55
}
func main() {
a := 58
fmt.Println("value of a before function call is", a)
b := &a
change(b)
fmt.Println("value of a after function call is", a)
}
value of a before function call is 58
value of a after function call is 55
package main
import "fmt"
func hello() *int {
i := 5
return &i
}
func main() {
d := hello()
fmt.Println("value of d", *d)
}