Adrian Coutsoftides
Adrian Coutsoftides

Reputation: 1293

Rust unpacking the contents of an enum

Rust noob here, I've been trying to unpack this enum from a grpc call (trying to access the Vec<u8> bytes) but so far I don't understand how I can access the underlying data.

Here is the proto:

message PublishRequest {
    string topic = 1;
    oneof optional_content {
        bytes content = 2;
    }
}

message KafkaResponse {
    bool success = 1;
    oneof optional_content {
        string content = 2;
    }
    
}

service KafkaStream {
    rpc Subscribe(stream PublishRequest) returns (stream KafkaResponse) {};
}

Rust code (I'm trying to reach PublishRequest.optional_content.content):

let output = async_stream::try_stream! {
            while let Some(publication) = stream.next().await {
                let message = publication?;
                let topic = message.topic.clone();
                if consumer_created_flag == false {
                    stream_topic = topic.clone();
                    consumer = Some(create_kafka_consumer(topic));
                    producer = Some(create_kafka_producer());
                    consumer_created_flag = true;
                }
                let content : Vec<u8> = match message.optional_content.clone() {
                    Some(message_content) => vec![], //trying to access content here instead
                    None =>vec![],
                };

                let reply = bridge::KafkaResponse {
                    content: format!("Hello {}!", "world"),
                };
                yield reply.clone();
            }
        };

message.optional_content is of type std::option::Option<bridge::publish_request::OptionalContent>

The underlying enum (from codegen):

pub mod publish_request {
    #[derive(Clone, PartialEq, ::prost::Oneof)]
    pub enum OptionalContent {
        #[prost(bytes, tag = "2")]
        Content(::prost::alloc::vec::Vec<u8>),
    }
}

Upvotes: 2

Views: 1221

Answers (1)

Netwave
Netwave

Reputation: 42716

You can match the whole type:

let content : Vec<u8> = match message.optional_content.clone() {
    Some(OptionalContent::Content(message_content)) => message_content,
    None =>vec![],
};

You can check the examples in the documentation

Upvotes: 3

Related Questions