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

问题描述:

是否可以将不同的 struct 构造函数传递给一个函数,以便它可以返回使用这些构造函数创建的不同值?

Is it possible to pass different struct constructors to a function so that it could return different values created with those constructors?

例如,我可能将 String10String20 传递给 createString 并且它应该根据传入的构造函数创建不同类型的值.

For example, I might pass String10 or String20 to createString and it should create a different type of value based on the constructor passed in.

我不知道如何设置 ctor 的类型和返回类型.我尝试了一个通用的 没有成功.

I don't know how to set the type for ctor nor the return type. I tried a generic <T> without success.

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

impl String10 {
    pub fn create(fieldName: &str, str: &str) -> String10 {
        // Failed to pass `String10` as a constructor to createString
        createString(fieldName, String10, 10, str)
    }
}

impl String20 {
    // same failure here
    pub fn create(fieldName: &str, str: &str) -> String10 {
        createString(fieldName, String20, 20, str)
    }
}

// Not sure what's the type for ctor and the return type?
pub fn createString<T>(fieldName: &str, ctor: T, maxLen: u32, str: &str) -> T {
    ctor(str);
}

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

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())
}

另见: