32-oneof使用

12 阅读1分钟

oneof使用

  • oneof的类型就是每次只能选择里面的一个使用,具体的类型需要到.pb.go文件中去查看

  • 目录结构如下: image.png

    1. go mod init protobuf_demo 初始化项目
    1. 创建api/notice.proto
    1. 书写notice.proto
syntax = "proto3";

package api;

option go_package = "protobuf_demo/api";

message NoticeRequest {
    string msg = 1;
    oneof notice_way {
        string email = 2;
        string phone = 3;
    }
}

message NoticeResponse {
    string msg = 1;
}


service Notice {
    rpc GetNotice(NoticeRequest) returns (NoticeResponse);
}
    1. protoc 生成.pb.go文件,这里先不用.grpc.go文件
    • protoc --proto_path=api --go_out=api --go_opt=paths=source_relative api/*.proto
    • 看到api文件夹下有个.pb.go文件生成就成功了
    • go mod tidy 把依赖安装一下
    1. 书写main.go
package main

import (
	"fmt"
	"protobuf_demo/api"
)

func oneofDemo() {
	req1 := &api.NoticeRequest {
		Msg: "Hello World",
		// 指定类型
		NoticeWay: &api.NoticeRequest_Phone{
			Phone: "19928283747",
		},
	}
	req2 := &api.NoticeRequest {
		Msg: "Hello World",
		// 指定类型
		NoticeWay: &api.NoticeRequest_Email{
			Email: "22333@qq.com",
		},
	}
	fmt.Printf("%v, %v\n", req1, req2)

	// 判断是哪个类型
	req := req1
	// 类型断言
	switch v := req.NoticeWay.(type) {
	case *api.NoticeRequest_Phone:
		fmt.Printf("Phone: %s\n", req.GetPhone())
		noticePhone(v)
	case *api.NoticeRequest_Email:
		fmt.Printf("Email: %s\n", req.GetEmail())
		noticeEmail(v)
	}
}

func noticePhone(in *api.NoticeRequest_Phone) {
	fmt.Printf("Phone: %s\n", in.Phone)
}

func noticeEmail(in *api.NoticeRequest_Email) {
	fmt.Printf("Email: %s\n", in.Email)
}

func main() {
    oneofDemo()
}
    1. go run main.go 运行
    1. 结果如下 image.png