struct User { name string email string country string}fn main() { user := User { name: "V developers" email: "developers@vlang.io" country: "Canada" }println(user.country)}
注意:结构是在堆栈上分配的。
创建结构的新实例时,可以使用逗号分隔每个字段。当您想在一行上创建一个新实例时,它很有用。
user := User { name: "V developers", email: "developers@vlang.io", country: "Canada" }
前缀&
您还可以在堆上分配一个结构,并使用&前缀获取对它的引用,如下所示:
user :=&User{"V developers", "developers@vlang.io", "Canada"}println(user.name)
struct User { email string// private and immutable (default)}
您可以将它们定义为private mutable。
struct User { email stringmut: first_name string// private mutable last_name string// (you can list multiple fields with the same access modifier)}
您还可以将它们定义为public immutable(只读)。
struct User { email stringmut: first_name string last_name stringpub: sin_number int// public immutable (readonly)}
或作为public,但仅在父模块中是mutable。
struct User { email stringmut: first_name string last_name stringpub: sin_number intpub mut: phone int// public, but mutable only in parent module}
或父模块内外的public和mutable。
struct User { email stringmut: first_name string last_name stringpub: sin_number intpub mut: phone int__global: address_1 string// public and mutable both inside and outside parent module address_2 string// (not recommended to use, that's why the 'global' keyword city string// starts with __) country string zip string}