欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

protobuf3 Any使用方法

程序员文章站 2022-07-04 10:23:22
...

前言

Any 定义的变量就是一个基础类,就像Java中的Object.class。

类似于声明变量,然后可以转成自己需要的任意类

BaseResult.proto 文件

syntax = "proto3";

package cn.api.base;

import "google/protobuf/any.proto";



message BaseResult{
  int32 ret = 1;
  string msg = 2;
  google.protobuf.Any foo = 3;
}

Example 1: Pack and unpack a message in C++.

 Foo foo = ...;
 Any any;
 any.PackFrom(foo);
 ...
 if (any.UnpackTo(&foo)) {
   ...
 }

Example 2: Pack and unpack a message in Java.

 Foo foo = ...;
 Any any = Any.pack(foo);
 ...
 if (any.is(Foo.class)) {
   foo = any.unpack(Foo.class);
 }

Example 3: Pack and unpack a message in Python.

 foo = Foo(...)
 any = Any()
 any.Pack(foo)
 ...
 if any.Is(Foo.DESCRIPTOR):
   any.Unpack(foo)
   ...

Example 4: Pack and unpack a message in Go

  foo := &pb.Foo{...}
  any, err := ptypes.MarshalAny(foo)
  ...
  foo := &pb.Foo{}
  if err := ptypes.UnmarshalAny(any, foo); err != nil {
    ...
  }