Home > Article > Backend Development > How can I export function names in compiled Go WASM files?
Exporting Function Names in Go WASM
You desire to export function names in compiled Go WASM files. By default, these names are not visible in the resulting .wasm file, making it difficult to call them from external contexts.
TinyGo's //export Directive
TinyGo, a Go compiler tailored for embedded and WASM environments, provides a solution to your problem. It supports the //export directive, which preserves function names during compilation. For example:
<code class="go">//export multiply func multiply(x, y int) int { return x * y; }</code>
This directive ensures that the multiply function remains accessible by its name in the compiled WASM file.
Standard Go Compiler Solution
For the standard Go compiler, there is an ongoing discussion about adding a similar feature. However, currently, you can achieve this by setting exported functions to the JS global namespace using js.Global().Set(...).
import ( "syscall/js" ) func main() { js.Global().Set("multiply", exportedMultiply) } //export multiply func exportedMultiply(this js.Value, args []js.Value) interface{} { if len(args) != 2 { return "Invalid number of arguments" } x, y := int(args[0].Int()), int(args[1].Int()) return x * y }
In this example, multiply is exported to the JS global scope, allowing it to be called from JavaScript using exports.multiply().
To build your Go WASM file, use the following command:
GOOS=js GOARCH=wasm go build -o main.wasm
The above is the detailed content of How can I export function names in compiled Go WASM files?. For more information, please follow other related articles on the PHP Chinese website!