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

3.4. String

Strings are regarded as basic data types in Wa-lang. The type name is: string. String literal constants are defined by double quotes "" and are encoded in UTF-8, for example:

    s: string = "你好,凹语言"
    println(s)     // 你好,凹语言
    println("+42") // +42

Similar to integers and floating point numbers, string variables can also be defined using short-declaration :=, for example:

    s := "编号9527"

Strings support add (+) binary operations, and the return value is the concatenation of two strings, for example:

    s1 := "abc"
    s2 := "123"
    println(s1 + s2) // abc123

The underlying structure that holds a string is a byte (that is, u8) array. You can use [] to get the value of a certain byte, or a substring, for example:

    s := "abcdefg"
    println(s[2])   // 99,the ASCII value of 'c'
    println(s[1:3]) // bc

In this usage, the subscripted units within [] are bytes, not characters. If the source string contains non-ASCII characters (such as Chinese characters) and the subscript is not at an right boundary, the returned substring may be illegal, for example:

    s := "你好"
    println(s[1:3]) // ��

s[m:n] operation starts from the mth byte, and the length of the returned string is n-m bytes. If m is omitted, it means start from the beginning of the string. If n is omitted, it means intercepting to the end of the string. For example:

    s := "abcdefg"
    println(s[:3]) // abc
    println(s[3:]) // defg

From the perspective of the underlying data, when intercepting the substring, there is no re-alloc for a byte array copy, but a direct reference to the address of the original string. In order to avoid the impact of mutual modification of multiple strings referencing the same memory, the string is set so that it cannot be modified locally - neither can it be assigned to s[n]. The following example are illegal:

    s := "abcdefg"
    s[0] = 99 // illegal

You can use the == and != operators to determine equality or inequality between two strings, for example:

    s := "abc"
    println(s == "123") // false
    println(s != "123") // true

The built-in function len can be used to get the length of a string in bytes, such as:

    s := "abcdefg"
    println(len(s)) // 7

List of known issues:

  • Bounds checking was not performed when using [] to obtain the specified bytes or substring of a string variable. 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.