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

  1. func NewInt(value ...int) *Int
  2. func (v *Int) Add(delta int) (new int)
  3. func (v *Int) Cas(old, new int) bool
  4. func (v *Int) Clone() *Int
  5. func (v *Int) Set(value int) (old int)
  6. func (v *Int) String() string
  7. func (v *Int) Val() int

Basic Usage

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/container/gtype"
  4. "fmt"
  5. )
  6. func main() {
  7. // Create a concurrently safe basic type object for Int
  8. i := gtype.NewInt()
  9. // Set the value
  10. fmt.Println(i.Set(10))
  11. // Get the value
  12. fmt.Println(i.Val())
  13. // Decrement by 1, and return the modified value
  14. fmt.Println(i.Add(-1))
  15. }

After execution, the output result is:

  1. 10
  2. 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
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gogf/gf/v2/container/gtype"
  6. )
  7. func main() {
  8. type Student struct {
  9. Id *gtype.Int
  10. Name *gtype.String
  11. Scores *gtype.Interface
  12. }
  13. s := Student{
  14. Id: gtype.NewInt(1),
  15. Name: gtype.NewString("john"),
  16. Scores: gtype.NewInterface([]int{100, 99, 98}),
  17. }
  18. b, _ := json.Marshal(s)
  19. fmt.Println(string(b))
  20. }

After execution, the output result:

  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/container/gtype"
  6. )
  7. func main() {
  8. b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
  9. type Student struct {
  10. Id *gtype.Int
  11. Name *gtype.String
  12. Scores *gtype.Interface
  13. }
  14. s := Student{}
  15. json.Unmarshal(b, &s)
  16. fmt.Println(s)
  17. }

After execution, the output result:

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