我有一個列舉String:
enum MyLovelyEnum {
Thing(String),
}
對于測驗,我希望能夠通過 a&'static str來避免MyLovelyEnum::Thing("abc".to_string)一遍又一遍。
我發現你可以用帶有建構式的結構很好地做到這一點:
// From: https://hermanradtke.com/2015/05/06/creating-a-rust-function-that-accepts-string-or-str.html
struct Person {
name: String,
}
impl Person {
fn new<S: Into<String>>(name: S) -> Person {
Person { name: name.into() }
}
}
fn main() {
let person = Person::new("Herman");
let person = Person::new("Herman".to_string());
}
我知道我可以使用生命周期或Cow如Rust 列舉中 str/String 值的最佳實踐是什么?或者我可以創建自己的函式。
是否有與列舉博客文章中的示例相似的內容?例如
// this is the kind of thing I am after but this specifically is not correct syntax
enum MyLovelyEnum {
Thing<S: Into<String>>(S)
}
uj5u.com熱心網友回復:
您可以創建一個通用列舉:
enum MyLovelyEnum<S>
where
S: Into<String>,
{
Thing(S),
}
MyLovelyEnum::Thing("a");
MyLovelyEnum::Thing("b".to_string());
我可能不會在我的代碼中這樣做,而是選擇創建一個建構式,就像您鏈接的博客文章一樣:
enum MyLovelyEnum {
Thing(String),
}
impl MyLovelyEnum {
fn thing(s: impl Into<String>) -> Self {
MyLovelyEnum::Thing(s.into())
}
}
MyLovelyEnum::thing("a");
MyLovelyEnum::thing("b".to_string());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/382302.html
