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."

5.1. Reference

In Wa-lang, adding the & symbol before a variable is called a reference operation. Assume that the type of the variable is T, and the type of the return value of the reference operation is *T, which is called It is a T-type reference, for example:

    i: i32 = 42
    j := &i // The type of j is *i32, that is: reference of i32

Adding the * symbol before a reference variable is called a dereference operation. The value of the dereference expression is the value of the original variable it refers to, for example:

    i: i32 = 42
    j := &i
    println(*j) // 42

Here *j returns the value of i, the same type as i is i32. Dereference can be assigned, which assigns a value to the referenced original variable, for example:

    i: i32 = 13
    j := &i
    *j = 42
    println(i) // 42

It can be seen that the reference in the Wa-lang is similar to the pointer in C language. However, since Wa-lang uses automatic memory management, this similarity only exists on the surface, so we use reference to indicate the difference. The most significant difference between the two can be seen through the following example:

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

func genI32Ref() => *i32 {
    i: i32 = 9527
    return &i
}

func main {
    p := genI32Ref()
    *p = 13
    q := genI32Ref()
    println(*p) // 13
    println(*q) // 9527
}

In Wa-lang, it is legal to pass references across functions. Returning a reference to a local variable is safe and harmless. The compiler and runtime will track the memory used by the variable and automatically perform cleanup. Of course, this leads to another intuitive difference between references and pointers, namely: references cannot perform arithmetic operations.

For reference type *T, T can be a basic type, or any composite type or custom type. Multi-level references like **T (similar to multi-level pointers in C language) are also legal.


List of known issues:

  • The currently used RC mode cannot automatically recycle orphaned rings, causing memory leaks. This problem does not affect syntax compatibility. Subsequent corrections to this problem will not affect the existing source code. Developers using Wa-lang do not need to deal with this issue specially.