The content on this page is written in Chinese, and then traslated into English by machine. More accurate traslations are welcome at: https://github.com/wa-lang/man/tree/master/en
Ending's law: "Any application that can be compiled to WebAssembly, will be compiled to WebAssembly eventually."
6.5. Anonymous structure
In the previous sections of this chapter, the structures we used were declared in the following form:
type StructName struct {
Member list
}
In fact, the inner meaning of this grammar is:
- The part of
struct {...}
defines a structure; - The
type StructName
part gives a name to the structure just defined.
So in Wa-lang, is it possible to directly create a structure variable by declaring a structure literal without naming the structure? It is indeed possible. This usage is called anonymous structure, for example:.
// 版权 @2021 凹语言 作者。保留所有权利。
//Global anonymous structure variable:
global G: struct{
name: string
age: i32
}
func main {
G.name = "张三"
G.age = 88
println(G.name, " ", G.age) // 张三 88
//local anonymous structure variable:
k := struct {name: string; age: i32}{name: "李四", age: 66}
println(k.name, " ", k.age) // 李四 66
G = k
println(G.name, " ", G.age) // 李四 66
}
Since anonymous structures do not have type names, when declaring anonymous structure variables, you can only use variable name: struct{...}
or its short-declaration form to directly specify the type (structure). In addition, the use of anonymous structures and their members is basically the same as ordinary named structures. Anonymous structures also follow the 0-value initialization rule. In their literal values, members with no initial value specified are all 0-value.
The most commonly used scenario for anonymous structures is global configuration variables. Many types of global configuration variables will only be used once when declaring the global variable. It is a bit cumbersome to define a separate type for a variable that only has one instance. In this case, an anonymous structure can be used instead (such as the global variable G
in the above example).
The named type is located in the namespace of the module, but because the anonymous structure has no name, its definition is actually located in the global space. Therefore, if the memory layout of the two anonymous structure variables is exactly the same (that is, the number of members, corresponding member names, and corresponding members types are consistent), they will be considered to belong to the same type and can be assigned to each other (such as the global variable G
and the local variable k
in the above example). This feature still holds even if the two variables are located in different modules. ; This leads to another usage scenario of anonymous structures: passing parameters across modules.
Since an anonymous structure has no type name, according to the syntax rules, methods cannot be added to it.