【发布时间】:2020-12-25 18:56:46
【问题描述】:
假设我们有以下枚举:
#[derive(Serialize)]
#[serde(untagged)]
pub enum CustomType {
Foo(Foo),
Bar(Bar),
}
为了使函数对不同的参数类型表现相同:
fn my_function(my_param: &CustomType){
// logic to use "my_param"
// my_param is used for the handlebars crate, therefore requires to be Serde Serializable
let source = // ...
handlebars.render_template(&source, my_param).unwrap();
}
我们想在程序的不同部分调用这样的函数,如下所示:
fn function_a(bar: &Bar){
my_function(CustomType::Bar(bar.clone()));
}
fn function_b(foo: &Foo){
my_function(CustomType::Foo(foo.clone()));
}
这段代码有效,但我真的不喜欢它,因为我必须.clone()。我已经尝试只传递引用,但它不适用于枚举。
这是在 Rust 中正确的做法吗?
【问题讨论】:
标签: generics types rust enums overloading