gvar

通用动态变量,支持各种内置的数据类型转换,可以作为interface{}类型的替代数据类型,并且该类型支持并发安全开关。

Tips: 框架同时提供了g.Var的数据类型,其实也是gvar.Var数据类型的别名。

使用场景

使用interface{}的场景,各种不固定数据类型格式,或者需要对变量进行频繁的数据类型转换的场景。

使用方式

  1. import "github.com/gogf/gf/container/gvar"

接口文档

https://godoc.org/github.com/gogf/gf/container/gvar

示例1,基本使用

  1. package main
  2. import (
  3. "github.com/gogf/gf/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. // struct转换
  19. type Score struct {
  20. Value int
  21. }
  22. s := new(Score)
  23. v.Struct(s)
  24. fmt.Println(s)
  25. }

执行后,输出结果为:

  1. 123
  2. 123
  3. 123
  4. 123
  5. [123]
  6. [123]
  7. [123]
  8. &{123}

示例2,JSON序列化/反序列

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

  1. Marshal

    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. "github.com/gogf/gf/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]}
  2. Unmarshal

    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. "github.com/gogf/gf/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]}