且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以将元组结构构造函数传递给函数以返回不同类型的值?

更新时间:2023-09-03 15:10:16

元组结构构造函数是函数.您可以将函数和闭包作为参数传递给其他函数.

Tuple struct constructors are functions. You can pass functions and closures as arguments to other functions.

pub struct String10(String);
pub struct String20(String);

impl String10 {
    pub fn create(field_name: &str, s: &str) -> String10 {
        create_string(field_name, String10, 10, s)
    }
}

impl String20 {
    pub fn create(field_name: &str, s: &str) -> String20 {
        create_string(field_name, String20, 20, s)
    }
}

pub fn create_string<T>(
    _field_name: &str,
    ctor: impl FnOnce(String) -> T,
    _max_len: u32,
    s: &str,
) -> T {
    ctor(s.to_string())
}

另见: