Go: wasm: No support for converting JS arrays into Go equivalent (inverse of TypedArrayOf())

Created on 8 Apr 2019  路  2Comments  路  Source: golang/go

What version of Go are you using (go version)?

$ go version 1.12

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output

$ go env
GOARCH="amd64"
GOOS="darwin"

What did you do?

This isn't a bug, but rather a WASM syscall/js feature suggestion. While syscall/js offers extremely helpful functionality for converting Go slices into JS arrays (specifically, func TypedArrayOf()), support for the inverse doesn't exist. This means that, to read a JS array passed into a Go function as a js.Value, one has the following options:

  1. Read elements from the JS array element by element, converting each value into the appropriate type before inserting it into a Go slice. (This is currently what is done in the example linked below). This works, but is clumsy
  2. Use the unsafe package to directly access the ref field in js.Value and use the js.Value's length to directly access the bytes starting at ref. Not ideal--requires using reflect to access ref, which is a private field.

As a result, passing JS arrays into Go functions in WASM requires extra lift and could benefit from an efficient JS array-to-Go slice conversion.


Check out the example code in
https://github.com/gabbifish/go-wasm-example/blob/master/main.go#L41-L53

What did you expect to see?

Support for converting JS arrays into Go arrays, given that the inverse logic already exists.

What did you see instead?

^ A hope that this functionality can be offered in Go WASM support in the future :) If there is interest, I'd be happy to work on a PR implementing functionality along these lines.

Arch-Wasm FeatureRequest FrozenDueToAge NeedsInvestigation

Most helpful comment

All 2 comments

Yet another approach is to pass the length of the JS array to Go, and create a slice, then pass the slice header pointer to JS and set the wasm linear memory with the JS array at that offset. Takes 2 hops, but does not require reflect.

This is coming up often. I think we should have a standard method in syscall/js before the community comes up with different methods.

@bradfitz @neelance

Was this page helpful?
0 / 5 - 0 ratings