结构体成员访问修饰符
结构体成员默认是私有并且不可修改的(结构体模式是只读)。但是可以通过pub设置为公开的,通过mut设置为可写的。总体来说有以下五种组合类型:
1. struct Foo {
2. a int // private immutable (default)
3. mut:
4. b int // private mutable
5. c int // (you can list multiple fields with the same access modifier)
6. pub:
7. d int // public immmutable (readonly)
8. pub mut:
9. e int // public, but mutable only in parent module
10. pub mut mut:
11. f int // public and mutable both inside and outside parent module
12. } // (not recommended to use, that's why it's so verbose)
例如在builtin模块定义的字符串类型:
1. struct string {
2. str byteptr
3. pub:
4. len int
5. }
可以看出字符串是一个只读类型。
字符串结构体中的byte指针在builtin模块之外不可访问。而len成员是模块外部可见的,但是外部是只读的。
1. fn main() {
2. str := 'hello'
3. len := str.len // OK
4. str.len++ // Compilation error
5. }
