Golang中WebAssembly编译错误解决方法

Golang中WebAssembly编译错误解决方法 我正在学习Go WebAssembly,偶然发现了这个教程: https://tutorialedge.net/golang/go-webassembly-tutorial/ 该教程在Go版本1.12.3 darwin/amd64上已经过时。 我发现js.NewCallback()不再可用。 新的函数调用js.FuncOf()让我很难理解。 有人能好心帮帮忙吗?

使用js.NewCallback()时的错误信息:

# command-line-arguments
./main.go:21:25: undefined: js.NewCallback

使用js.FuncOf()时的错误信息:

# command-line-arguments
./main.go:21:34: cannot use add (type func([]js.Value)) as type func(js.Value, []js.Value) interface {} in argument to js.FuncOf

这是我的main.go文件:

package main

import (
 "strconv"
 "syscall/js"
 //"github.com/dennwc/dom/js"
)

func add(i []js.Value) {
 value1 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
 value2 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()

 int1, _ := strconv.Atoi(value1)
 int2, _ := strconv.Atoi(value2)

 js.Global().Get("document").Call("getElementById", i[2].String()).Set("value", int1+int2)

 //c <- true
}

func registerCallbacks() {
 js.Global().Set("add", js.FuncOf(add))
}

func main() {
 c := make(chan struct{}, 0)

 println("WASM Go Initialized")
 // register functions
 registerCallbacks()
 <-c
}

更多关于Golang中WebAssembly编译错误解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

谢谢先生 我会仔细研究的

更多关于Golang中WebAssembly编译错误解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你好,

我在这里维护一些Go WebAssembly的示例:

简单示例: https://github.com/Yaoir/ClockExample-Go-WebAssembly
复杂示例: https://github.com/Yaoir/VideoPoker-Go-WebAssembly

这两个示例都已更新,支持Go 1.12版本。

希望能对你有所帮助。

问题在于js.FuncOf()需要与js.NewCallback()不同的函数签名。js.FuncOf()期望的函数类型是func(this js.Value, args []js.Value) interface{},而你的add函数签名是func(i []js.Value)

以下是修正后的代码:

package main

import (
 "strconv"
 "syscall/js"
)

func add(this js.Value, args []js.Value) interface{} {
 value1 := js.Global().Get("document").Call("getElementById", args[0].String()).Get("value").String()
 value2 := js.Global().Get("document").Call("getElementById", args[1].String()).Get("value").String()

 int1, _ := strconv.Atoi(value1)
 int2, _ := strconv.Atoi(value2)

 js.Global().Get("document").Call("getElementById", args[2].String()).Set("value", int1+int2)

 return nil
}

func registerCallbacks() {
 js.Global().Set("add", js.FuncOf(add))
}

func main() {
 c := make(chan struct{}, 0)

 println("WASM Go Initialized")
 registerCallbacks()
 <-c
}

主要修改:

  1. add函数签名改为func(this js.Value, args []js.Value) interface{}
  2. 将函数内所有的i改为args
  3. 函数返回nil(因为需要返回interface{}类型)

编译命令保持不变:

GOOS=js GOARCH=wasm go build -o main.wasm main.go

这个修正后的版本应该能正常编译并运行在当前的Go WebAssembly环境中。

回到顶部