基本使用

  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. // 基本类型转换
  11. fmt.Println(v.Int())
  12. fmt.Println(v.Uint())
  13. fmt.Println(v.Float64())
  14. // slice转换
  15. fmt.Println(v.Ints())
  16. fmt.Println(v.Floats())
  17. fmt.Println(v.Strings())
  18. }

执行后,输出结果为:

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

JSON 序列化/反序列

gvar.Var 容器实现了标准库 json 数据格式的序列化/反序列化接口。

  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. }

执行后,输出结果:

  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. }

执行后,输出结果:

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