为什么装箱变量需要显式类型才能传递给函数? [重复]

问题描述 投票:1回答:1

为什么要进行此编译需要显式类型?我希望编译器在第一个测试用例中理解Box<STest>等于Box<(dyn TTest + 'static)>,因为STest实现了TTest特征。是什么使编译器能够在第二种情况下将其隐式转换为BoxedTTest,而在第一种情况下却没有呢?

我正在rustc --edition 2018 mwe.rs(稳定)上使用rustc 1.40.0对其进行编译,但是在--edition 2015rustc 1.42.0-nightly上会发生相同的错误。

trait TTest {}

struct STest {}
impl TTest for STest {}

type BoxedTTest = Box<dyn TTest>;

fn foo(_test: &BoxedTTest) {}

pub fn main() {
    // expected trait TTest, found struct `STest`
    let test1 = Box::new(STest {});
    foo(&test1);

    // OK
    let test2: BoxedTTest = Box::new(STest {});
    foo(&test2);
}

完整错误如下:

error[E0308]: mismatched types
  --> mwe.rs:13:9
   |
13 |     foo(&test1);
   |         ^^^^^^ expected trait TTest, found struct `STest`
   |
   = note: expected type `&std::boxed::Box<(dyn TTest + 'static)>`
              found type `&std::boxed::Box<STest>`
rust traits box
1个回答
0
投票

在这种情况下,答案不是像这样使用Box。正如Stargateur在评论中所建议的,以下是解决方法:

trait TTest {}

struct STest {}
impl TTest for STest {}

fn foo(_test: &dyn TTest) {}

pub fn main() {
    // OK
    let test1 = STest {};
    foo(&test1);
}

例如,如果仍然需要使用Box将其存储在矢量中,则仅应在严格需要的地方使用它:

fn add_test(test: Box<dyn TTest>) {
    let mut vec = vec!{};
    vec.push(test);
}
// ...
add_test(Box::new(test1));
© www.soinside.com 2019 - 2024. All rights reserved.