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.2. Method

In addition to encapsulating member data, the biggest role of structures is that they can have methods. In Wa-lang, method is a special type of function that is attached to a specific type, see the following example:

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

type Info struct {
    name: string
    age:  i32
}

// method declaration:
func Info.Print {
    println("Name:", this.name, ", Age:", this.age)
}

func main {
    i := Info{name: "Tom", age: 35}
    i.Print() // Name: Tom , Age: 35
}

The general form of method declaration is as follows:

func TypeName.MethodName(parameter list) => (Return value list) {method function body}

The difference between method declaration and ordinary global function declaration is that TypeName. is added to the function name. Inside the method body, this is a reference to the type to which the method belongs, and its members can be read and written through this..

If we only look at the syntax that has been introduced so far, methods and global functions can accomplish the same task. For example, the above example is almost equivalent to the following code:

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

type Info struct {
    name: string
    age:  i32
}

func Print(this: *Info) {
    println("Name:", this.name, ", Age:", this.age)
}

func main {
    i := Info{name: "Tom", age: 35}
    Print(&i) // Name: Tom , Age: 35
}

As shown in the above example, if the first parameter of the global function is set to a reference of a custom type, its role is almost the same as that of the method. In fact, in Wa-lang, from a runtime perspective, the method is a function whose first parameter is a reference to a custom type. So why bother introducing this concept? There are two reasons:

  1. Methods help aggregate the functionality of an object;
  2. The concept of interface is directly dependent on methods - the set of methods of a type determines the interface it implements, which is introduced in Chapter 7.

It is important to note that according to the concave language syntax, the method declared using func T.xxx()... does not belong to type T, but to type *T; That is to say, the named type itself cannot have methods, and only the reference of the named type can have methods.