Is it possible to pass a tuple struct constructor to a function to return different types of values?

让人想犯罪 __ 提交于 2021-02-08 02:59:11

问题


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

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.

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

回答1:


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

See also:

  • In Rust how do you pass a function as a parameter?


来源:https://stackoverflow.com/questions/58736827/is-it-possible-to-pass-a-tuple-struct-constructor-to-a-function-to-return-differ

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!