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.3. Method values

Since methods are also functions, you can use them following the pattern in Section 4.2, for example:

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

type Vertex struct{
    x, y: i32
}

func Vertex.Scale(s: i32) {
    this.x *= s
    this.y *= s
}

func Vertex.Sub(s: i32) {
    this.x -= s
    this.y -= s
}

func Vertex.Print {
    println("x:", this.x, "y:", this.y)
}

func FnOp(s: i32) {
    println("FnOp, s:", s)
}

func main {
    v := Vertex{x: 100, y:200}
    op : func(s: i32)

    op = FnOp // op此时是函数值FnOp
    op(13) // FnOp, s: 13

    op = v.Scale // op此时是方法值v.Scale
    op(2)
    v.Print() // x: 200 y: 400

    op = v.Sub // op此时是方法值v.Sub
    op(50)
    v.Print() // x: 150 y: 350
}

v.Scale and v.Sub are methods of the structure variable v. When they are used as values, they are called method values. For example, in the above example, they are assigned to op. The method value can be called like an ordinary function value, and the call can affect the reference associated with the method (just like calling the original method directly). It can be seen that the method value captures the original object reference and is stateful. At this point, method values are similar to closures.

From the above example, we can also know that function value variables (such as op in the example) can store both function values and method values. For the caller, there is no difference between the two.