我想实现一个函数,它接受不可变的&Vec引用,制作副本,对值进行排序并打印它们。
这是主要代码。
trait Foo {
fn value(&self) -> i32;
}
struct Bar {
x: i32,
}
impl Foo for Bar {
fn value(&self) -> i32 {
self.x
}
}
fn main() {
let mut a: Vec<Box<dyn Foo>> = Vec::new();
a.push(Box::new(Bar { x: 3 }));
a.push(Box::new(Bar { x: 5 }));
a.push(Box::new(Bar { x: 4 }));
let b = &a;
sort_and_print(&b);
}
Run Code Online (Sandbox Code Playgroud)
我能够让它发挥作用的唯一方法就是这个
fn sort_and_print(v: &Vec<Box<dyn Foo>>) {
let mut v_copy = Vec::new();
for val in v {
v_copy.push(val);
} …Run Code Online (Sandbox Code Playgroud) rust ×1