1

I'm using tonic framework, a rust grpc server implementation. In the generated rust code from the proto file, I have a struct which has a field:

#[prost(message, optional, tag="3")]
pub data: ::core::option::Option<::prost_types::Value>,

generated from a protobuff field:

google.protobuf.Value data = 3; 

I can't seem to find a way to init data which is type prost_types::Value by converting a struct I have. I'm doing something like:

prost_types::Value::try_from(myOwnsStructVar)

But it does not work. Anyone have used prost_types lib before and know how to encode/convert to prost_types::Value

myOwnsStructVar is a type struct. I need to convert it to prost_types::Struct So then I can do:

prost_types::value::Kind::StructValue(myOwnsStructVarAfterConversiontToProstStruct)
Noor Thabit
  • 79
  • 2
  • 10

1 Answers1

1

Just from looking at the docs, we can see that Value is a struct with a single public field kind which is of type Option<Kind>. The docs say that if this field is None then that indicates an error. If you look at the docs for Kind, then it's apparent this is where the actual data is stored. So if you want to initialize something of type Value then you'd want to do something like the following, substituting in the appropriate variant of Kind for your use case:

Value {
    kind: Some(Kind::NumberValue(10.0f64))
}

The reason that your try_from solution didn't work is because there are no TryFrom implementations for Value other than the default blanket implementation.

Ian S.
  • 1,831
  • 9
  • 17
  • Thank you very much. I have a struct that I want to assign it to `data`. ` prost_types::value::Kind::StructValue(myOwnStructVar)`I need to convert it to `prost_types::Struct` which is gonna be hard because cause its `BTreeMap<::prost::alloc::string::String, Value>`. Any idea how? – Noor Thabit May 12 '22 at 13:00
  • @NoorThabit Similar to `Value`, `prost_types::Struct` has a public field called `fields` of that type, so you can just do `prost_types::Struct { fields: my_btree_map }`. If you're not familiar with structurally initializing Rust types then I would check out the relevant sections of [the book](https://doc.rust-lang.org/book/). – Ian S. May 12 '22 at 17:19
  • Thanks I appreciate it. This would be a solution but its not ideal, cause i have to populate the map manually. – Noor Thabit May 12 '22 at 17:54
  • Ah I think I understand better what you were asking now. Looking for some `serde` extension similar to the crate you mentioned here is probably the way to go to make that conversion as painless as possible. – Ian S. May 12 '22 at 18:27