相关疑难解决方法(0)

什么时候我不应该实现引用该特征的实现者的特征?

如果我有一个特征,并且接受一个约束到该类型的泛型类型的函数,一切正常.如果我尝试传入对该类型的引用,我会收到编译错误.

trait Trait {
    fn hello(&self) -> u32;
}

struct Struct(u32);

impl Trait for Struct {
    fn hello(&self) -> u32 {
        self.0
    }
}

fn runner<T: Trait>(t: T) {
    println!("{}", t.hello())
}

fn main() {
    let s = Struct(42);

    // Works
    runner(s);

    // Doesn't work
    runner(&s);
}
Run Code Online (Sandbox Code Playgroud)
error[E0277]: the trait bound `&Struct: Trait` is not satisfied
  --> src/main.rs:24:5
   |
24 |     runner(&s);
   |     ^^^^^^ the trait `Trait` is not implemented for `&Struct`
   |
   = help: the following implementations were found: …
Run Code Online (Sandbox Code Playgroud)

reference traits rust

15
推荐指数
2
解决办法
1534
查看次数

为什么借临时是合法的?

来自C++,我很惊讶这段代码在Rust中是有效的:

let x = &mut String::new();
x.push_str("Hello!");
Run Code Online (Sandbox Code Playgroud)

在C++中,你不能取一个临时的地址,一个临时的不会比它出现的表达式更长.

临时居住在Rust多久了?既然x只是借用,谁是字符串的所有者?

temporary rust

13
推荐指数
3
解决办法
1254
查看次数

为引用和非引用类型实现特征会导致实现冲突

我正在尝试创建一个特征并为所有非引用类型提供一个实现,并为所有引用类型提供另一个实现.

这无法编译:

trait Foo {}
impl<T> Foo for T {}
impl<'a, T> Foo for &'a mut T {}
Run Code Online (Sandbox Code Playgroud)

这失败了,错误

error[E0119]: conflicting implementations of trait `Foo` for type `&mut _`:
 --> src/main.rs:3:1
  |
2 | impl<T> Foo for T {}
  | -------------------- first implementation here
3 | impl<'a, T> Foo for &'a mut T {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `&mut _`
Run Code Online (Sandbox Code Playgroud)

奇怪的是,这有效:

trait Bar {}

impl<T> Bar for T
where
    T: Clone,
{}

impl<'a, T> Bar for &'a mut T …
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
2
解决办法
475
查看次数

标签 统计

rust ×3

reference ×1

temporary ×1

traits ×1