在 Go 中,可寻址的表达式包括变量、指针间接引用、切片索引表达式、结构体字段选择表达式和数组索引表达式。不可寻址的表达式包括常量、基本类型字面量、字符串字面量、函数字面量和不可寻址的接收器值。下面是一些示例代码:
package main
import "fmt"
func main() {
a := 1
b := &a // 取 a 的地址
c := []int{1, 2, 3}
d := &c[0] // 取 c 中第一个元素的地址
e := struct{ x int }{a}
f := &e.x // 取 e 的字段 x 的地址
fmt.Println("&a : ", &a) // 输出:a 的地址
fmt.Println("&c[0] : ", &c[0]) // 输出:c 中第一个元素的地址
fmt.Println("&e.x : ", &e.x) // 输出:e 的字段 x 的地址
fmt.Println("b : ", b) // 输出:a 的地址
fmt.Println("*b : ", *b) // 输出:a 的值
fmt.Println("*d : ", *d) // 输出:c 中第一个元素的值
fmt.Println("*f : ", *f) // 输出:e 的字段 x 的值
// 不可寻址的表达式
fmt.Println("&1 : ", &1) // 编译错误:cannot take the address of 1
fmt.Println("&true : ", &true) // 编译错误:cannot take the address of true
fmt.Println("&'a' : ", &'a') // 编译错误:cannot take the address of 'a'
fmt.Println("&\"foo\" : ", &"foo")// 编译错误:cannot take the address of "foo"
fmt.Println("&func : ", &func(){}) // 编译错误:cannot take the address of func
}
在上面的示例代码中,我们使用 & 运算符来获取变量和表达式的地址,如果表达式不可寻址,会导致编译错误。同时我们还使用 * 运算符来获取指针所指向的值。