小编Fra*_*dom的帖子

为什么我不能在 Rust 中的 Drop 中使用 Deref 特征?

我实现了结构Deref的特征,它允许我通过orMyString使用类型的对象。MyString*oo.deref()

但是,当我实现该Drop特征MyString时,已经实现的Deref特征就不能在该特征内部使用Drop。为什么?

use std::ops::Deref;
use std::ops::DerefMut;

struct MyString {
    s: String,
}

impl Deref for MyString {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.s
    }
}

impl DerefMut for MyString {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.s
    }
}

impl Drop for MyString {
    fn drop(&mut self) {
        // println!("string dropped: {}", *self); // `MyString` doesn't implement `std::fmt::Display`
        // …
Run Code Online (Sandbox Code Playgroud)

traits dereference rust drop

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

我可以用 Rust 编写一个不可变变量

  let mut a = Box::new("123".to_string());
  let b = Box::new( &mut a);

  b.push('4');

  assert_eq!( "1234", b.as_str());

  // lets see the types:
  // let x001: Box<&mut Box<String>> = b;
  // let x001:&mut Box<String> = *b;
  // let x001:Box<String> = **b;
  // let x001:String = ***b;
  // let x001:str = ****b;

  let c = Box::new("456".to_string());

  **b = c;

  b.push('9');
  (*b).push('9');
  (**b).push('9');
  (***b).push('9');
  // (****b).push('9'); // no method named `push` found for type `str` in the current scope

  // c.push( 'a'); // cannot mutate …
Run Code Online (Sandbox Code Playgroud)

immutability ownership mutability rust

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

标签 统计

rust ×2

dereference ×1

drop ×1

immutability ×1

mutability ×1

ownership ×1

traits ×1