Use trait for close type alias

I have this closure type alias:

type ClosureType = Box<Fn(i32) -> i32>;

this trait:

trait Trait {
    fn change(&self, y: i32) -> i32;
}

and these functions:

fn with_one(x: Box<Fn(i32) -> i32>) -> i32 {
    x(1)
}

fn plus_one(x: i32) -> i32 {
    x+1
}

fn main() {
    let a = Box::new(|x: i32|{x+1});
    let b: ClosureType = Box::new(|x: i32|{x+1});
    let c = Box::new(plus_one);
    let d: ClosureType = Box::new(plus_one);
    println!("{}", a.change(1));
    println!("{}", b.change(1));
    println!("{}", c.change(1));
    println!("{}", d.change(1));
    println!("{}", with_one(a));
    println!("{}", with_one(b));
    println!("{}", with_one(c));
    println!("{}", with_one(d));
}

When I implement a tag Traitfor ClosureTypeor for Box<Fn(i32) -> i32>, which is the same if I understand the type aliases correctly:

impl Trait for ClosureType {
    fn change(&self, y: i32) -> i32{
        self(y)
    }
}

or

impl Trait for Box<Fn(i32) -> i32> {
    fn change(&self, y: i32) -> i32{
        self(y)
    }
}

for the variable aI get:

<anon>:32:22: 32:31 error: no method named `change` found for type
`Box<[closure <anon>:28:22: 28:35]>` in the current scope 
<anon>:32     println!("{}", a.change(1));

and for the variable, cI get:

<anon>:34:22: 34:31 error: no method named `change` found for type
`Box<fn(i32) -> i32 {plus_one}>` in the current scope
<anon>:34     println!("{}", c.change(1));

However, the variables are aalso caccepted from the function with_one(x: Box<Fn(i32) -> i32>) -> i32, in other words, it seems that they have the same type ( Box<Fn(i32) -> i32>) for the function with_one, but different ( Box<[closure <anon>:24:22: 24:35]>and Box<fn(i32) -> i32 {plus_one}) for implementation Trait.

I feel something is missing here, but not sure what it is, could you enlighten me?

You can find all the code in this site with rust .

+4
1

, - ( ) .

with_one(), , -, :

with_one(a as Box<Fn(i32) -> i32>);
with_one(c as Box<Fn(i32) -> i32>);

b d let s.

. ( - Self ). , Rust :

trait MyStringLike {}

impl<'a> MyStringLike for &'a str {}

fn function<T: MyStringLike>(t: T) {}

let s: String = "abcde".into();
function(&s);  // the trait `main::MyStringLike` is not implemented for the type `&collections::string::String`
+4

All Articles