gtype并发安全基本类型的使用非常简单,往往就类似以下几个方法(以gtype.Int类型举例):

func NewInt(value ...int) *Int
func (v *Int) Add(delta int) (new int)
func (v *Int) Cas(old, new int) bool
func (v *Int) Clone() *Int
func (v *Int) Set(value int) (old int)
func (v *Int) String() string
func (v *Int) Val() int

基本使用

package main

import (
    "github.com/gogf/gf/v2/container/gtype"
    "fmt"
)

func main() {
    // 创建一个Int型的并发安全基本类型对象
    i := gtype.NewInt()

    // 设置值
    fmt.Println(i.Set(10))

    // 获取值
    fmt.Println(i.Val())

    // 数值-1,并返回修改之后的数值
    fmt.Println(i.Add(-1))
}

执行后,输出结果为:

0
10
9

JSON序列化/反序列

gtype模块下的所有容器类型均实现了标准库json数据格式的序列化/反序列化接口。

1、Marshal 

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gogf/gf/v2/container/gtype"
)

func main() {
    type Student struct {
        Id     *gtype.Int
        Name   *gtype.String
        Scores *gtype.Interface
    }
    s := Student{
        Id:     gtype.NewInt(1),
        Name:   gtype.NewString("john"),
        Scores: gtype.NewInterface([]int{100, 99, 98}),
    }
    b, _ := json.Marshal(s)
    fmt.Println(string(b))
}

执行后,输出结果:

{"Id":1,"Name":"john","Scores":[100,99,98]}

2、Unmarshal

package main


import (
    "encoding/json"
    "fmt"
    "github.com/gogf/gf/v2/container/gtype"
)


func main() {
    b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
    type Student struct {
        Id     *gtype.Int
        Name   *gtype.String
        Scores *gtype.Interface
    }
    s := Student{}
    json.Unmarshal(b, &s)
    fmt.Println(s)
}

执行后,输出结果:

{1 john [100,99,98]}