Home > OS >  Sprintf shows <number: 19> instead of 19 on js.Value
Sprintf shows <number: 19> instead of 19 on js.Value

Time:11-17

In my code I'm getting a js.Value that is a simple object {"Age":19}

For displaying it, I used:

data := fmt.Sprintf("Age: %v", value.Get("age"))
fmt.Println(data)

But the output was:

Age: <number: 19> 

Expected output is:

Age: 19 

Once I replaced the %v by %d to be:

data := fmt.Sprintf("Age: %v", value.Get("age"))
fmt.Println(data)

I got:

Age: {[] 4626041242239631360 0}

CodePudding user response:

js.Value.Get returns a js.Value again, and js.Value implements fmt.Stringer interface. The output you see is the result of calling Value.String() on an instance that wraps js.TypeNumber

String returns the value v as a string. String is a special case because of Go's String method convention. Unlike the other getters, it does not panic if v's Type is not TypeString. Instead, it returns a string of the form "" or "<T: V>" where T is v's type and V is a string representation of v's value.

Use Value.Int() or Value.Float() to unwrap the numerical value:

data := fmt.Printf("Age: %d", value.Get("age").Int())

This instead {[] 4626041242239631360 0} is the string representation of the Value struct itself with its internals. For reference:

type Value struct {
    _     [0]func() // uncomparable; to make == not compile
    ref   ref       // identifies a JavaScript value, see ref type
    gcPtr *ref      // used to trigger the finalizer when the Value is not referenced any more
}

CodePudding user response:

The documentation for js.Value shows that the result of Get is another Value struct, and not an integer. So when you print the resulting js.Value with %v, it goes to the default formatter for a js.Value, which prints the type as well as the value.

When you explicitly told it to print it as %d, it prints the Value struct as numbers, which in this case means an empty array a ref struct and a *ref pointer, as you can see in the code: https://golang.org/src/syscall/js/js.go

What you probably want is to call the Int() method, which returns the value as an integer:

data := fmt.Sprintf("Age: %d, value.Get("Age").Int())
fmt.Println(data)
  • Related