Skip to main content
Version: 2.8.x(Latest)

The use of gtype concurrent safe basic types is very simple, often similar to the following methods (taking the gtype.Int type as an example):

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

Basic Usage

package main

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

func main() {
// Create a concurrently safe basic type object for Int
i := gtype.NewInt()

// Set the value
fmt.Println(i.Set(10))

// Get the value
fmt.Println(i.Val())

// Decrement by 1, and return the modified value
fmt.Println(i.Add(-1))
}

After execution, the output result is:

10
9

JSON Serialization/Deserialization

All container types under the gtype module implement the serialization/deserialization interface of the standard library json data format.

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

After execution, the output result:

{"Id":1,"Name":"john","Scores":[100,99,98]}
  1. 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)
}

After execution, the output result:

{1 john [100,99,98]}