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);
看了半天没发现有什么问题啊,求大神解答
1
共 3 条评论, 1 页
评论区
写评论感谢 明白咋回事了
trait相当于一个接口,要给特定的结构体实现,然后通过结构体去调用
trait是用来实现的