protoファイルで定義されているenumは、prost-buildによってRustの列挙型に変換される。
この列挙型は、::prost::Enumerationマクロが適用されている。
Snazzyの例。
enum Size {
SMALL = 0;
MEDIUM = 1;
LARGE = 2;
}
↓prost-buildによる変換
#[repr(i32)]
pub enum Size {
Small = 0,
Medium = 1,
Large = 2,
}
impl Size {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
Self::Small => "SMALL",
Self::Medium => "MEDIUM",
Self::Large => "LARGE",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option {
match value {
"SMALL" => Some(Self::Small),
"MEDIUM" => Some(Self::Medium),
"LARGE" => Some(Self::Large),
_ => None,
}
}
}
文字列リテラル(&str)と変換するメソッドが生成されている。
let mut s = Shirt {
color: ProstString::from("abc"),
size: Size::Large.into(), // 構造体にセットする初期値としては、列挙型からinto()でi32に変換する
};
println!("Shirt = {:?}", s);
let size = s.size(); // フィールドはi32だが、構造体にはゲッターメソッドが生成されていて、列挙型で受け取れる
s.set_size(Size::Medium); // 構造体には列挙型で受け取るセッターメソッドが生成されている
prostが生成する列挙型には、::prost::Enumerationマクロによって生成されるメソッドがある。[2024-10-12]
| メソッド | 説明 | 例 |
|---|---|---|
from_str_name(value:
&str) -> Option<Self> |
列挙子名の文字列から列挙型に変換する。 | let e = Size::from_str_name("Large").unwrap(); |
as_str_name(&Size)
-> &str |
列挙型から列挙子名の文字列に変換する。 | let s = Size::Large.as_str_name(); |
is_valid(value:
i32) -> bool |
数値が列挙子に変換できるかどうか。 | let b = Size::is_valid(0); |
try_from(value:
i32) -> Result<Self, Error> |
数値から列挙子に変換する。 | let e = Size::try_from(0).unwrap(); |
try_into(self) ->
Result<T, Error> |
列挙子から数値に変換する。 | let n: i32 = e.try_into().unwrap(); |
into(self) -> T |
列挙子から数値に変換する。 | let n: i32 = e.into(); |