Basic Usage

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "fmt"
  5. )
  6. func main() {
  7. var v g.Var
  8. v.Set("123")
  9. fmt.Println(v.Val())
  10. // Basic type conversion
  11. fmt.Println(v.Int())
  12. fmt.Println(v.Uint())
  13. fmt.Println(v.Float64())
  14. // Slice conversion
  15. fmt.Println(v.Ints())
  16. fmt.Println(v.Floats())
  17. fmt.Println(v.Strings())
  18. }

After execution, the output is:

  1. 123
  2. 123
  3. 123
  4. 123
  5. [123]
  6. [123]
  7. [123]

JSON Serialization/Deserialization

The gvar.Var container implements the serialization/deserialization interface of the standard library json data format.

  1. Marshal
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gogf/gf/v2/frame/g"
  6. )
  7. func main() {
  8. type Student struct {
  9. Id *g.Var
  10. Name *g.Var
  11. Scores *g.Var
  12. }
  13. s := Student{
  14. Id: g.NewVar(1),
  15. Name: g.NewVar("john"),
  16. Scores: g.NewVar([]int{100, 99, 98}),
  17. }
  18. b, _ := json.Marshal(s)
  19. fmt.Println(string(b))
  20. }

After execution, the output is:

  1. {"Id":1,"Name":"john","Scores":[100,99,98]}
  1. Unmarshal
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gogf/gf/v2/frame/g"
  6. )
  7. func main() {
  8. b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
  9. type Student struct {
  10. Id *g.Var
  11. Name *g.Var
  12. Scores *g.Var
  13. }
  14. s := Student{}
  15. json.Unmarshal(b, &s)
  16. fmt.Println(s)
  17. }

After execution, the output is:

  1. {1 john [100,99,98]}