gpt4 book ai didi

generics - 如何调用许多不同类型的函数?

转载 作者:行者123 更新时间:2023-12-03 11:41:29 24 4
gpt4 key购买 nike

假设我们有以下枚举:

#[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中做的正确方法吗?

最佳答案

如果不想调用CustomType,可以使clone接受引用而不是拥有的值:

use serde::{Serialize};

#[derive(Serialize)]
struct Foo(String);

#[derive(Serialize)]
struct Bar(String);

#[derive(Serialize)]
#[serde(untagged)]
enum CustomType<'a> {
Foo(&'a Foo),
Bar(&'a Bar),
}

fn my_function(my_param: &CustomType) {
println!("serialized {}", serde_json::to_string(&my_param).unwrap());
}

fn func_foo(foo: &Foo) {
my_function(&CustomType::Foo(foo));
}

fn func_bar(bar: &Bar) {
my_function(&CustomType::Bar(bar));
}

fn main() {
let foo = Foo("Foo".to_string());
let bar = Bar("Bar".to_string());
func_foo(&foo);
func_bar(&bar);
}
playground
但是,如果 CustomType存在的唯一原因是您可以将 Serializable类型传递给 my_function,则使 my_function通用并接受任何 Serializable引用可能会更简单:
use serde::{Serialize};

#[derive(Serialize)]
struct Foo(String);

#[derive(Serialize)]
struct Bar(String);

fn my_function<T: Serialize>(my_param: &T) {
println!("serialized {}", serde_json::to_string(my_param).unwrap());
}

fn main() {
let foo = Foo("Foo".to_string());
let bar = Bar("Bar".to_string());
my_function(&foo);
my_function(&bar);
}
playground

关于generics - 如何调用许多不同类型的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65450905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com