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.1. Structure

The general form of structure declaration in Wa-lang is:

type StructName struct {
    Member list
}

The member list part is consistent with the variable declaration format, such as the following example:

// 版权 @2023 凹语言 作者。保留所有权利。

type Info struct {
    name: string
    age:  i32
}

func PrintInfo(i: Info) {
    println("Name:", i.name, ", Age:", i.age)
}

func main {
    i: Info
    i.name = "张三"
    i.age = 35
    PrintInfo(i) // Name: 张三 ,Age: 35
}

Like many languages, Wa-lang use the selection operator . to access members of a structure value. In addition, it is important to note that the selection operator . can also be used to access members of a structure reference, for example:

// 版权 @2023 凹语言 作者。保留所有权利。

type Info struct {
    name: string
    age:  i32
}

func GetInfo() => *Info {
    i: Info
    i.name = "李四"
    i.age = 42
    return &i
}

func main {
    j := GetInfo() // The type of j is a reference, *Info
    println(j.name, j.age) // 李四 42
}

It can be seen that whether it is a value or a reference, the way to access its members is the same, which is different from C language (C language uses -> to access members of structure pointers).

The type of the structure members cannot be the structure itself, because this will cause infinite nesting; in fact, any structure that will cause infinite nesting is illegal, such as two structures containing each other. However, it is legal for a structure to contain references of this type (because the essence of a reference is a pointer). This usage is often used to create linked list structures, such as:

type Node struct {
    data: i32
    next: *Node
}

Examples of structure literals are as follows:

// 版权 @2023 凹语言 作者。保留所有权利。

type Info struct {
    name: string
    age:  i32
}

func main {
    i := Info{name: "王五"}
    println(j.name, j.age) // 王五 0
}

When declaring a structure literal, {} contains a list of member literals, and unlisted members have a value of 0.

If all member variables in the structure are comparable (that is, the == operation can be performed between variables of the member type), then the variables of the structure are also comparable. Among the data types introduced so far, slices are incomparable types, so structures that directly or indirectly contain slices are not comparable. Similar to other types of declarations, structures can be declared in any file within the module, and there is no need to "declare before using".