以下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 trait
或if..else
时,在返回位置使用match
的正确方法是什么?