[go]go addressable 详解

go addressable 详解

// 常数为什么不可以寻址?
因为常量是不可变的。(如果可寻址,那可能会通过地址修改它,违背了常量定义)

// 为什么字符串中的字符(字节)又不能寻址呢?
因为字符串是不可变的。

// 为什么slice不管是否可寻址,它的元素都是可以寻址的?
因为 slice 底层实现了一个数组,它是可以寻址的。

// map 的元素为什么不可以寻址?
两个原因,1. 如果对象不存在,则返回零值,零值是不可变对象,所以不能寻址,
        2. 如果对象存在,因为 Go 中 map 实现中元素的地址是变化的,这意味着寻址的结果是无意义的。

参考
go语言规范中对Address_operators说明

//可寻址

variable
pointer indirection, 
slice indexing operation
a field selector of an addressable struct operand
an array indexing operation of an addressable array.


一个变量: &x
指针引用(pointer indirection): &*x
slice 索引操作(不管 slice 是否可寻址): &s[1]
可寻址 struct 的字段: &point.X
可寻址数组的索引操作: &a[0]
composite literal 类型: &struct{ X int }{1}
字符串中的字节:
map对象中的元素
接口对象的动态值(通过type assertions获得)
常数
literal值(非composite literal)
package 级别的函数
方法method (用作函数值)
中间值(intermediate value):
    函数调用
    显式类型转换
    各种类型的操作 (除了指针引用pointer dereference操作 *x):
        channel receive operations
        sub-string operations
        sub-slice operations
        加减乘除等运算符

猜你喜欢

转载自www.cnblogs.com/iiiiiher/p/12152031.html