我正在开发一个 Rust 项目,使用 Protocol Buffers 并处理嵌套枚举。这是我迄今为止在 Rust 中所拥有的:
enum Vehicle {
Car(CarType),
Truck(TruckType),
}
enum CarType {
Sedan,
Coupe,
Hatchback,
}
enum TruckType {
Pickup,
Semi,
}
fn create_vehicle_fleet() -> [Vehicle; 8] {
[
Vehicle::Car(CarType::Sedan),
Vehicle::Truck(TruckType::Pickup),
Vehicle::Car(CarType::Coupe),
Vehicle::Truck(TruckType::Semi),
Vehicle::Car(CarType::Hatchback),
Vehicle::Car(CarType::Sedan),
Vehicle::Truck(TruckType::Pickup),
Vehicle::Car(CarType::Coupe),
]
}
我找不到在 protobuf 中表示车辆枚举的正确方法。任何人都可以提出解决方案或提供有关如何在 Protocol Buffers 中处理这种情况的指导吗?
我怀疑(!?)由于协议缓冲区的语言无关性,您不能总是直接使用原型来表示特定于语言的类型。
在这种情况下,Rust 具有强大、复杂的枚举类型,但 Protocol Buffers 只允许常量枚举。
我认为(!?)几乎相当于你需要的是:
syntax = "proto3";
// package something;
// Only messages can hold repeateds
message Foo {
repeated Vehicle vehicles = 1;
}
// oneof permits the equivalent of a enum of non-constant types
// In some languages, the oneof name is lost but in rust it is retained
// See code snippet below
message Vehicle {
oneof vehicle_type {
CarType car_type = 1;
TruckType truck_type = 2;
}
}
// Constant enums
// If CarType|TruckType ever need fields too,
// this enum would need to be oneof
enum CarType {
Sedan = 0;
Coupe = 1;
Hatchback = 2;
}
enum TruckType {
Pickup = 0;
Semi = 1;
}
并且,例如:
pub mod anoynmous {
tonic::include_proto!("_");
}
use anonymous::{
vehicle::VehicleType,
CarType,
Foo,
TruckType,
Vehicle,
};
fn main() {
let _ = Foo {
vehicles: vec![
Vehicle {
vehicle_type: Some(VehicleType::CarType(CarType::Sedan.into())),
},
Vehicle {
vehicle_type: Some(VehicleType::TruckType(TruckType::Pickup.into())),
},
],
};
}