Skip to content

Instantly share code, notes, and snippets.

@ehfeng
Created June 21, 2023 15:18
Show Gist options
  • Save ehfeng/d6000ba41d14008eab88f055782dae2c to your computer and use it in GitHub Desktop.
Save ehfeng/d6000ba41d14008eab88f055782dae2c to your computer and use it in GitHub Desktop.
How pointers works with primitives vs objects in v8go
package main
import (
"fmt"
v8 "rogchap.com/v8go"
)
func main() {
iso := v8.NewIsolate()
ctx1 := v8.NewContext(iso)
ctx2 := v8.NewContext(iso)
// primitives are copied, but the old pointers to still point to the old ones
v1, err := v8.NewValue(iso, int32(1))
if err != nil {
panic(err)
}
fmt.Println("ctx1 value", v1)
if err := ctx2.Global().Set("x", v1); err != nil {
panic(err)
}
v2, err := ctx2.Global().Get("x")
if err != nil {
panic(err)
}
fmt.Println("ctx2 value", v2)
if _, err := ctx2.RunScript("x++", "main.js"); err != nil {
panic(err)
}
fmt.Println("post-increment ctx2 value", v2)
incrementedV2, err := ctx2.Global().Get("x")
if err != nil {
panic(err)
}
fmt.Println("incremented ctx2 value", incrementedV2)
fmt.Println("ctx1 value after increment", v1)
// values are copied, are pointers to objects shared?
fmt.Printf("\n\nObject stuff\n\n")
objPtr, err := v8.JSONParse(ctx1, `{"a": 1}`)
if err != nil {
panic(err)
}
s, err := v8.JSONStringify(ctx1, objPtr)
if err != nil {
panic(err)
}
fmt.Println("ctx1", s)
if err := ctx2.Global().Set("x", objPtr); err != nil {
panic(err)
}
if _, err := ctx2.RunScript("x.a++", "main.js"); err != nil {
panic(err)
}
objPtr2, err := ctx2.Global().Get("x")
if err != nil {
panic(err)
}
s2, err := v8.JSONStringify(ctx2, objPtr2)
if err != nil {
panic(err)
}
fmt.Println("ctx2, should be two", s2)
s, err = v8.JSONStringify(ctx1, objPtr)
if err != nil {
panic(err)
}
fmt.Println("ctx1", s)
// yes, pointers reference the same object across contexts
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment