【发布时间】:2021-09-22 11:25:09
【问题描述】:
我正在学习 Rust,但不明白为什么以下内容不起作用。我想我们无法在 trait 对象上克隆 Rc 指针?如some_function 中所尝试的,我如何将此类引用传递给仅由特征定义的函数?
use std::rc::Rc;
trait SomeTrait {}
struct SomeThing {}
impl SomeTrait for SomeThing {}
fn some_function(s: Rc<dyn SomeTrait>) {}
fn another_function(s: &Rc<dyn SomeTrait>) {}
fn main() {
let s = Rc::new(SomeThing{});
// This doesnt work
some_function(Rc::clone(&s));
// I could do this
some_function(s);
// But then I could not do this
some_function(s);
// For that matter, neither can I do this
another_function(&s);
}
【问题讨论】:
标签: rust traits smart-pointers trait-objects