< 返回版块

Lexo-0 发表于 2021-05-02 23:10

Tags:Fn|trait|impl


trait Run{
    fn run(&self,name:String,speed:u64) -> String;
}

impl <T>Run for T
    where T:Fn(String) -> String
{
    fn run(&self,name:String,_:u64) -> String{
        self(name)
    }
}

fn unknown_speed(name:String) -> String{
    format!("{} 's speed is unknown",name)
}

fn main(){
    let runner1:&dyn Run=&unknown_speed;
    let result1=runner1.run("rabbit".to_string(),0);
    println!("{}",result1);
}

这段代码可以正常运行。


trait Run{
    fn run(&self,name:String,speed:u64) -> String;
}

impl <T>Run for T
    where T:Fn(String) -> String
{
    fn run(&self,name:String,_:u64) -> String{
        self(name)
    }
}

impl <T>Run for T
    where T:Fn(String,u64) -> String
{
    fn run(&self,name:String,speed:u64) -> String{
        self(name,speed)
    }
}

fn unknown_speed(name:String) -> String{
    format!("{} 's speed is unknown",name)
}

fn with_speed(name:String,speed:u64) -> String{
    format!("{} 's speed is {}",name,speed)
}

fn main(){
    let runner1:&dyn Run=&unknown_speed;
    let result1=runner1.run("rabbit".to_string(),0);
    
    let runner2:&dyn Run=&with_speed;
    let result2=runner2.run("dog".to_string(),100);

    println!("{}",result1);
    println!("{}",result2);

}

这段代码无法运行

error[E0119]: conflicting implementations of trait `Run`:
  --> src/main.rs:13:1
   |
5  | / impl <T>Run for T
6  | |     where T:Fn(String) -> String
7  | | {
8  | |     fn run(&self,name:String,_:u64) -> String{
9  | |         self(name)
10 | |     }
11 | | }
   | |_- first implementation here
12 | 
13 | / impl <T>Run for T
14 | |     where T:Fn(String,u64) -> String
15 | | {
16 | |     fn run(&self,name:String,speed:u64) -> String{
17 | |         self(name,speed)
18 | |     }
19 | | }
   | |_^ conflicting implementation

一个函数不可能既实现Fn(String),又实现Fn(String,u64),两个trait实现根本不冲突!如何解决这个问题?

问题代码playground链接:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=11cc0cbf3dba66b9bf27fb96466ad1c7


Ext Link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=11cc0cbf3dba66b9bf27fb96466ad1c7

评论区

写评论
w 2021-05-06 10:01

rust不支持函数和方法的重载,因此我觉得fn(string)fn(string,u64)在编译器看来是一个类型

gwy15 2021-05-03 09:56

可以按照这里的方法解决: https://gwy15.com/blog/%E7%B1%BB%E5%9E%8B%E6%93%A6%E9%99%A4%E6%95%99%E7%A8%8B-Part-I.-%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84%E5%90%8C%E6%AD%A5%E7%A4%BA%E8%8C%83

gwy15 2021-05-03 09:55

谁告诉你不可能的?

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=de9929db7f157dd56712f9261dcd5db4

1 共 3 条评论, 1 页