GoFrame gtype-基本使用

2022-04-08 14:29 更新

?gtype?并發(fā)安全基本類型的使用非常簡單,往往就類似以下幾個方法(以?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() {
    // 創(chuàng)建一個Int型的并發(fā)安全基本類型對象
    i := gtype.NewInt()

    // 設(shè)置值
    fmt.Println(i.Set(10))

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

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

執(zhí)行后,輸出結(jié)果為:

0
10
9

JSON序列化/反序列

?gtype?模塊下的所有容器類型均實現(xiàn)了標(biāo)準(zhǔn)庫?json?數(shù)據(jù)格式的序列化/反序列化接口。

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

執(zhí)行后,輸出結(jié)果:

{"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)
}

執(zhí)行后,輸出結(jié)果:

{1 john [100,99,98]}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號