2

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);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Don Klein
  • 215
  • 2
  • 8

1 Answers1

4

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366