---
title: "安全类型-基本使用"
url: "https://goframe.org/docs/components/container-gtype-example"
markdown_url: "https://goframe.org/docs/components/container-gtype-example.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "组件列表"
category: "组件列表 / 数据结构 / 安全类型-gtype"
published: "2024-10-21"
updated: "2024-11-13"
description: "在GoFrame框架中使用gtype模块实现并发安全的基本类型操作。通过示例代码展示了如何创建和操作线程安全的基本类型，如整数类型的增减操作，以及gtype容器类型的JSON序列化和反序列化功能，帮助开发者便捷地管理数据。"
keywords: ["GoFrame", "GoFrame框架", "gtype", "并发安全", "JSON序列化", "Go语言", "基本使用", "线程安全", "容器类型", "数据操作"]
---

# 安全类型-基本使用

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

```go
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
```

## 基本使用

```go
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`

```go
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`

```go
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]}
```
