如果有条件语句,如何在返回位置使用impl trait

时间:2019-07-17 20:54:44

标签: function rust traits

以下Rust片段将编译并运行:

trait Trait: std::fmt::Debug {}

impl Trait for i32 {}
impl Trait for String {}

fn returns_a_trait_object(i: i32) -> Box<dyn Trait> {
    if i > 1 {
        Box::new(5)
    } else {
        Box::new(String::from("mmm"))
    }
}

fn main() {
    println!("{:?}", returns_a_trait_object(0));
}

impl Trait功能旨在允许编写此代码without using Box

以下代码段无法编译:

trait Trait: std::fmt::Debug {}

impl Trait for i32 {}
impl Trait for String {}

fn returns_a_trait_object(i: i32) -> impl Trait {
    if i > 1 {
        5
    } else {
        String::from("mmm")
    }
}

fn main() {
    println!("{:?}", returns_a_trait_object(0));
}

它失败并显示:

error[E0308]: if and else have incompatible types
  --> src/main.rs:10:9
   |
7  | /     if i > 1 {
8  | |         5
   | |         - expected because of this
9  | |     } else {
10 | |         String::from("mmm")
   | |         ^^^^^^^^^^^^^^^^^^^ expected integer, found struct `std::string::String`
11 | |     }
   | |_____- if and else have incompatible types
   |
   = note: expected type `{integer}`
              found type `std::string::String`

当您有条件语句(例如impl traitif..else时,在返回位置使用match的正确方法是什么?

0 个答案:

没有答案