如何使用google.protobuf.Struct?

发布于:2024-05-09 ⋅ 阅读:(26) ⋅ 点赞:(0)

google.golang.org/protobuf/types/known/structpb 包提供了一种方式来创建和操作 google.protobuf.Struct 类型的数据。google.protobuf.Struct 是一种灵活的数据类型,可以表示任何结构化数据。

以下是如何使用 structpb 包的一些示例:

  1. 创建 Struct
import (
	"google.golang.org/protobuf/types/known/structpb"
)

func createStruct() (*structpb.Struct, error) {
    // 创建一个 map 来存储我们的数据
    data := map[string]interface{}{
        "name": "John Doe",
        "age":  30,
        "emails": []interface{}{
            "johndoe@example.com",
            "johndoe@gmail.com",
        },
        "isVerified": true,
    }

    // 使用 structpb.NewStruct 函数将 map 转换为 Struct
    return structpb.NewStruct(data)
}
  1. Struct 中读取数据:
import (
	"fmt"
	"google.golang.org/protobuf/types/known/structpb"
)

func readStruct(s *structpb.Struct) {
    // 使用 AsMap 函数将 Struct 转换为 map
    data := s.AsMap()

    // 从 map 中读取数据
    name := data["name"].(string)
    age := data["age"].(int64)
    emails := data["emails"].([]interface{})
    isVerified := data["isVerified"].(bool)

    fmt.Printf("Name: %s\n", name)
    fmt.Printf("Age: %d\n", age)
    fmt.Printf("Emails: %v\n", emails)
    fmt.Printf("Is Verified: %v\n", isVerified)
}

注意:在从 Struct 读取数据时,需要进行类型断言,因为 AsMap 函数返回的是 map[string]interface{} 类型的数据。

使用具体的结构体

你可以定义一个具体的结构体来代替 map[string]interface{}。这样做的好处是类型更明确,代码更易读,而且可以利用 Go 的类型系统进行编译时检查。

以下是如何使用具体的结构体来创建 google.protobuf.Struct

首先,定义你的结构体。例如,我们可以定义一个 User 结构体:

type User struct {
    Name       string   `json:"name"`
    Age        int64    `json:"age"`
    Emails     []string `json:"emails"`
    IsVerified bool     `json:"isVerified"`
}

然后,你可以使用 json.Marshal 将你的结构体转换为 JSON,再使用 jsonpb.Unmarshal 将 JSON 转换为 google.protobuf.Struct

import (
    "encoding/json"
    "google.golang.org/protobuf/types/known/structpb"
)

func createStructFromUser(user User) (*structpb.Struct, error) {
    // 将 User 结构体转换为 JSON
    jsonData, err := json.Marshal(user)
    if err != nil {
        return nil, err
    }

    // 创建一个新的 Struct
    pbStruct := &structpb.Struct{}

    // 使用 jsonpb.Unmarshal 将 JSON 转换为 Struct
    if err := jsonpb.UnmarshalString(string(jsonData), pbStruct); err != nil {
        return nil, err
    }

    return pbStruct, nil
}

这样,你就可以使用具体的结构体来创建 google.protobuf.Struct 了。


网站公告

今日签到

点亮在社区的每一天
去签到