是否可以将元组结构构造函数传递给函数以返回不同类型的值? [英] Is it possible to pass a tuple struct constructor to a function to return different types of values?

查看:42
本文介绍了是否可以将元组结构构造函数传递给函数以返回不同类型的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将不同的 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())
}

另见:

这篇关于是否可以将元组结构构造函数传递给函数以返回不同类型的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆