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