Trait mismatch for function argument

前端 未结 2 558
孤独总比滥情好
孤独总比滥情好 2021-01-22 15:09

I\'ve got one piece of Rust code that compiles and one that\'s very similar that does not.

The one that works:

pub fn do_something(_: Box

        
2条回答
  •  孤独总比滥情好
    2021-01-22 15:46

    You can't coerce a Box> into a Box>>, for reasons discussed in this question, but you can coerce the inner Box:

    pub fn do_something(_: Box>>) {}
    
    fn main() {
        let iter = Box::new(Box::new(vec![1.0].into_iter()) as Box>);
        //                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        do_something(iter);
    }
    

    Playground.

    This works because a cast is a coercion site. By writing as Box>, you're hinting to the compiler that it should attempt to make the expression to the left fit that type instead of inferring Box>, because once it's wrapped up in the "outer" Box, you can't change it anymore.

    Alternatively (but less clearly), you could make Box::new(...) a coercion site by explicitly parameterizing Box:

        let iter = Box::>>::new(Box::new(vec![1.0].into_iter()));
    

    Which effectively does the same thing.

提交回复
热议问题