相关疑难解决方法(0)

为什么std :: rc :: Rc <>不能复制?

有人可以向我解释为什么Rc<>不是Copy吗?

我正在编写使用大量共享指针的代码,并且不得不一直打字,.clone()这让我很紧张.

在我看来,Rc<>应该只是一个指针,这是一个固定的大小,所以类型本身应该是Sized,因此Copy,对吗?

我错过了什么吗?

smart-pointers rust

19
推荐指数
2
解决办法
1895
查看次数

哪种类型对方法的`self`参数有效?

我想创建一个仅在self参数为的情况下工作的方法Rc.我看到我可以使用Box,所以我想我可能会尝试模仿它是如何工作的:

use std::rc::Rc;
use std::sync::Arc;

struct Bar;

impl Bar {
    fn consuming(self) {}
    fn reference(&self) {}
    fn mutable_reference(&mut self) {}
    fn boxed(self: Box<Bar>) {}
    fn ref_count(self: Rc<Bar>) {}
    fn atomic_ref_count(self: Arc<Bar>) {}
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

产生这些错误:

error[E0308]: mismatched method receiver
  --> a.rs:11:18
   |
11 |     fn ref_count(self: Rc<Bar>) {}
   |                  ^^^^ expected struct `Bar`, found struct `std::rc::Rc`
   |
   = note: expected type `Bar`
   = note:    found type `std::rc::Rc<Bar>`

error[E0308]: mismatched method receiver
  --> …
Run Code Online (Sandbox Code Playgroud)

methods syntax rust

13
推荐指数
1
解决办法
2866
查看次数

是否可以将 trait 对象转换为另一个 trait 对象?

我尝试了以下代码:

trait TraitA {
    fn say_hello(&self) {
        self.say_hello_from_a();
    }
    fn say_hello_from_a(&self);
}

trait TraitB {
    fn say_hello(&self) {
        self.say_hello_from_b();
    }
    fn say_hello_from_b(&self);
}

struct MyType {}

impl TraitA for MyType {
    fn say_hello_from_a(&self) {
        println!("Hello from A");
    }
}

impl TraitB for MyType {
    fn say_hello_from_b(&self) {
        println!("Hello from B");
    }
}

fn main() {
    let a: Box<dyn TraitA> = Box::new(MyType {});
    let b: Box<dyn TraitB>;

    a.say_hello();
    b = a;
    b.say_hello();
}
Run Code Online (Sandbox Code Playgroud)

我收到以下编译错误:

error[E0308]: mismatched types
  --> src/main.rs:34:9
   |
34 …
Run Code Online (Sandbox Code Playgroud)

casting dynamic rust

8
推荐指数
1
解决办法
4135
查看次数

标签 统计

rust ×3

casting ×1

dynamic ×1

methods ×1

smart-pointers ×1

syntax ×1