【问题标题】:Does Rc::deref return a reference? [duplicate]Rc::deref 是否返回引用? [复制]
【发布时间】:2018-01-21 03:49:42
【问题描述】:

以下代码:

use std::rc::Rc;

fn main() {
    let s = Rc::new(String::from("Hello"));
    let o: &String = *s;
}

给我这个错误:

  = note: expected type `&std::string::String`
             found type `std::string::String`

我预计*s 会提供某种参考,因为deref 签名是fn deref(&self) -> &T

让我感到困惑的一件事是,如果我将 let o 行更改为:

let o: String = *s;

我现在收到cannot move out of borrowed content 的错误。

所以我有两个相关的问题

  1. 为什么 Rc 值的 *s 不返回引用?
  2. 我知道引用不能移动,*s 是借用而不是引用?我以为这些词的意思是一样的?

【问题讨论】:

    标签: rust


    【解决方案1】:

    *s 不会扩展为 s.deref(),而是扩展为 *(s.deref())。这是因为* 运算符的主要功能是取消引用指针。直观地说,无论s 是普通指针还是智能指针,您都希望*s 不返回指针(除非s 是指向指针的指针)。这种扩展保留了这种直觉。

    【讨论】:

    • 啊,谢谢!为了明确回答第二个问题,*(s.deref()) 是不允许的,因为s.deref() 是借用的(参考)。
    猜你喜欢
    • 2015-10-15
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多