< 返回版块

w 发表于 2021-03-12 14:55


 
    use std::fmt::Debug;

    // struct A{};

    trait A {
        fn get_some(t: u8) -> Box<dyn Debug> {
            match t {
                0 => {
                    Box::new("asdaasd")
                },
                _ =>{
                    Box::new(32)
                }
            }
        }
    }

    let some = A::get_some(0);
    let some = A::get_some(1);


error[E0283]: type annotations needed
  --> src/main.rs:84:16
   |
72 |         fn get_some(t: u8) -> Box<dyn Debug> {
   |         ------------------------------------ required by `A::get_some`
...
84 |     let some = A::get_some(0);
   |                ^^^^^^^^^^^ cannot infer type
   |
   = note: cannot satisfy `_: A`

需要将trait A改为 struct A才可以

    use std::fmt::Debug;

    struct A{};

    impl A {
        fn get_some(t: u8) -> Box<dyn Debug> {
            match t {
                0 => {
                    Box::new("asdaasd")
                },
                _ =>{
                    Box::new(32)
                }
            }
        }
    }

    let some = A::get_some(0);
    let some = A::get_some(1);

看了半天没发现有什么问题啊,求大神解答

评论区

写评论
作者 w 2021-03-12 17:07

感谢 明白咋回事了

Cupnfish 2021-03-12 16:55

trait相当于一个接口,要给特定的结构体实现,然后通过结构体去调用

Eliot00 2021-03-12 15:54

trait是用来实现的

1 共 3 条评论, 1 页