【问题标题】:How can I automatically apply the From trait to convert to a generic argument type when invoking a function?调用函数时,如何自动应用 From 特征转换为泛型参数类型?
【发布时间】:2020-09-30 21:45:50
【问题描述】:

在下面的代码中显式使用String::from 有效,但我怎样才能让它自动使用From<OsStringWrap<'a>> 特征而不显式使用String::from

use serde::Serialize; // 1.0.115

struct OsStringWrap<'a>(&'a std::ffi::OsString);
impl<'a> From<OsStringWrap<'a>> for String {
    fn from(s: OsStringWrap) -> String {
        s.0.to_string_lossy().to_string()
    }
}

pub fn insert<T: Serialize + ?Sized, S: Into<String>>(_key: S, _value: &T) {}

fn main() {
    for (key, value) in std::env::vars_os() {
        // HOW-TO: auto use From<OsStringWrap<'a>> trait
        // without explicit `String::from` like below?
        /*
            insert(OsStringWrap(&key), &OsStringWrap(&value))
        */

        // below using `String::from` to make it explicitly
        // but want to find a way to make it shorter
        insert(OsStringWrap(&key), &String::from(OsStringWrap(&value)))
    }
}

Playgroundinsert 方法是来自tera 的真实案例

【问题讨论】:

标签: rust


【解决方案1】:

您目前的要求是不可能的。您的 insert 函数接受泛型类型,因此不存在告诉编译器应转换为哪种类型。这个小例子是等价的:

fn demo<T>(_: T) {}

fn main() {
    demo(true.into());
}

由于编译器无法知道要选择转换为哪种具体类型,因此程序员必须指定它。

您可能会更改您的函数以接受可以转换为String(例如T: Into&lt;String&gt;)或被引用为&amp;str(例如T: AsRef&lt;str&gt;)的任何内容。

另见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多