鉴于此代码:
trait Base {
fn a(&self);
fn b(&self);
fn c(&self);
fn d(&self);
}
trait Derived : Base {
fn e(&self);
fn f(&self);
fn g(&self);
}
struct S;
impl Derived for S {
fn e(&self) {}
fn f(&self) {}
fn g(&self) {}
}
impl Base for S {
fn a(&self) {}
fn b(&self) {}
fn c(&self) {}
fn d(&self) {}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不能投&Derived给&Base:
fn example(v: &Derived) {
v as &Base;
}
Run Code Online (Sandbox Code Playgroud)
error[E0605]: non-primitive cast: `&Derived` as `&Base`
--> …Run Code Online (Sandbox Code Playgroud) 我的目标是打印具有特征对象成员的结构的内容,但我找不到如何告诉 Rust 编译器该成员还实现了其他特征,例如Displayor Debug。
例如,在下面的程序中,我想打印 的结构S2(并S1进行比较),但我陷入了 的实现中fmt。
trait Tr {}
impl Tr for usize {}
impl Tr for String {}
#[derive(Debug)]
struct S1<A: Tr + std::fmt::Debug> {
member: Box<A>,
}
struct S2 {
member: Box<Tr>,
}
impl std::fmt::Debug for S2 {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
// ??
Ok(())
}
}
fn main() {
let s1 = S1 {
member: Box::new(String::from("abc")),
};
println!("{:?}", s1);
let s2 = …Run Code Online (Sandbox Code Playgroud) 在 Rust 中,我想要一个包含实现 2 个特征的项目的 vec。但是,当我尝试像这样实现它时,我收到错误only auto traits can be used as additional traits in a trait object:
let mut v : Vec<Box<dyn MyTrait + std::fmt::Display>> = Vec::new();
Run Code Online (Sandbox Code Playgroud)
FairPlay,我完整阅读了错误消息并定义了一个结合了两者的 Trait:
pub trait FormattableDoer: std::fmt::Display + MyTrait{}
Run Code Online (Sandbox Code Playgroud)
它们有一个 Vec of Boxes:
let mut v: Vec<Box<dyn FormattableDoer>> = Vec::new();
Run Code Online (Sandbox Code Playgroud)
然而,编译器似乎无法检测到我的结构已经单独实现了这些东西,并且我收到了错误the trait bound MyStruct: FormattableDoer is not satisfied。
我读到过有关使用特征别名的信息,但它不稳定,所以我宁愿不使用它。
这在生锈中可能吗?这似乎是一件很常见的事情,但我很惊讶答案并不简单(或者也许很简单,但我错过了!)。我也在想,也许我处理这个问题的方法完全错误,我正在尝试以“不生锈”的方式做一些事情。如果是这样的话,拥有可显示且具有其他特征的事物向量的首选方式是什么?
带有 MWE 和用例的Playground 。
如果我有一长串必须在很多地方重复的类型界限,我该如何给它们命名?
例如,如果不是:
fn foo<T: Thing>(t: T) -> T
where T: Copy, T: Debug { ... }
Run Code Online (Sandbox Code Playgroud)
我想写:
fn foo<T: Thing>(t: T) -> T
where T: CopyDebug { ... }
Run Code Online (Sandbox Code Playgroud)
在哪里CopyDebug定义为Copy+Debug?