Function fn类型的实现特征

Function fn类型的实现特征,function,rust,traits,Function,Rust,Traits,我想为几个具体的函数实现定制特性,例如 trait ToTarget { fn custom_str(&self) -> String; } impl ToTarget for fn() -> String { fn custom_str(&self) -> String { self() } } impl ToTarget for fn(i32) -> String { fn custom_str(&a

我想为几个具体的函数实现定制特性,例如

trait ToTarget {
    fn custom_str(&self) -> String;
}

impl ToTarget for fn() -> String {
    fn custom_str(&self) -> String {
        self()
    }
}

impl ToTarget for fn(i32) -> String {
    fn custom_str(&self) -> String {
        self(4)
    }
}

fn a() -> String {
    "abc".to_string()
}

fn b(x: i32) -> String {
    x.to_string()
}

fn main() {
    println!("{}", b.custom_str());
}
但是,如果出现下一个错误,则不会编译:

<anon>:26:22: 26:34 error: no method named `custom_str` found for type `fn(i32) -> collections::string::String {b}` in the current scope
<anon>:26     println!("{}", b.custom_str());
                               ^~~~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:25: 2:56 note: expansion site
<std macros>:1:1: 2:62 note: in expansion of print!
<std macros>:3:1: 3:54 note: expansion site
<std macros>:1:1: 3:58 note: in expansion of println!
<anon>:26:5: 26:36 note: expansion site
<anon>:26:22: 26:34 help: items from traits can only be used if the trait is implemented and in scope; the following trait defines an item `custom_str`, perhaps you need to implement it:
<anon>:26:22: 26:34 help: candidate #1: `ToTarget`
error: aborting due to previous error
playpen: application terminated with error code 101
所以问题是:有没有办法让我的第一个版本的代码

println!("{}", b.custom_str());

编译?每次我想使用我的trait时指定函数类型真的很烦人。

问题是每个函数都有自己的类型,但可能与另一个函数具有相同的签名。对于签名为
fn(i32)->String的所有函数,您都实现了trait
ToTarget

例如:您的函数
b
具有类型
fn(i32)->集合::字符串::字符串{b}
(请注意类型中的
{b}
),但不能显式指定此类型

您可以为实现
Fn(i32)->String的所有类型实现
ToTarget

trait ToTarget {
    fn custom_str(&self) -> String;
}

impl<T> ToTarget for T where T: Fn(i32) -> String {
    fn custom_str(&self) -> String {
        self(4)
    }
}

fn b(x: i32) -> String {
    x.to_string()
}
trait to target{
fn自定义字符串(&self)->字符串;
}
T的impl-ToTarget,其中T:Fn(i32)->字符串{
fn自定义\u str(&self)->字符串{
自我(4)
}
}
fn b(x:i32)->字符串{
x、 to_string()
}

但是您不能为
Fn()->String
或任何其他类型实现
ToTarget
,因为可能有一个类型实现了
Fn(i32)->String
Fn()->String
,这将为同一类型生成两个不同的实现。据我所知,即使在这里也没有帮助,所以你运气不好。

我不确定这会有什么影响,但也许可以不费吹灰之力地确保所有具有相同签名的函数都可以强制加入该签名。谢谢你的回答。我的第一次尝试是为trait实现
ToTarget
,但是当我编写第二次实现时,我发现我不能为trait实现第二次ToTarget。我想在这种特殊情况下,我会切换到宏。
trait ToTarget {
    fn custom_str(&self) -> String;
}

impl<T> ToTarget for T where T: Fn(i32) -> String {
    fn custom_str(&self) -> String {
        self(4)
    }
}

fn b(x: i32) -> String {
    x.to_string()
}