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."
2.5. Import declaration
The import declaration starts with the keyword import
, and the general syntax is as follows:
import path
For example:
// 版权 @2023 凹语言 作者。保留所有权利。
import "errors"
func main {
err := errors.New("!!!")
println("err:", err.Error())
}
func getAnswer => i32 {
return 42
}
The import "errors"
declaration at the beginning of the program imports the built-in errors
module, and the public objects of this module can be used in subsequent functions - such as the errors.New
function in the example; .
in It is called the selection operator here. Its meaning is to select the object (module) on the left with the same name as the one on the right. In addition to selecting functions and global functions exposed by the module, Objects such as variables are also used to select members of structures (see Chapter 6 for details).
Import declarations should precede all non-import declarations within the source file (i.e., in the header, immediately after the file header comment). If you import multiple modules, you can use brackets to import them in groups, like this:
import (
"errors"
"strconv"
)
This is equivalent to the following:
import "errors"
import "strconv"
When importing a module, you can give the module an alias. The general syntax is as follows:
import path => alias
This can solve the problem of name conflict when importing two modules with different paths but the same name at the same time, for example:
import (
"errors"
"mypackage/errors" => myerrors
)
func main {
err := errors.New("!!!") // Call the built-in errors module
myerr := myerrors.New("!!!") // Call the mypackage/errors module块
}
Unlike other declarations, the scope of the import declaration is the current source file. If two source files in a module use the same third-party module, then their import declarations are required in both files.
In Wa-lang, every module imported by a source file must be used, that is, if a module is imported but none of its objects are used, it will be considered a syntax error.