簡體   English   中英

Rust。 在全局 scope 中使用 impl 函數的困惑

[英]Rust. Confusion around using functions from impl in global scope

我正在做 Rust 書中的示例,但我不明白這一點。 tail()List的實現中是 function 並且aRc類型時, a.tail()如何使用tail()

use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Debug)]
enum List {
    Cons(i32, RefCell<Rc<List>>),
    Nil,
}

impl List {
    fn tail(&self) -> Option<&RefCell<Rc<List>>> {
        match self {
            Cons(_, item) => Some(item),
            Nil => None,
        }
    }
}

fn main() {
    let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));

    println!("a initial rc count = {}", Rc::strong_count(&a));
    println!("a next item = {:?}", a.tail());
}

謝謝

Rc實現Deref 這意味着您可以執行&*rc並返回&T ,就像它是一個參考一樣。

當您調用方法時,編譯器會根據需要自動插入&* 這稱為 autoref 或 autoderef。 請參閱Rust 的確切自動取消引用規則是什么? 更多細節。

這是由於自動取消引用或Deref強制。 Rc是一個引用計數的智能指針,它實現了Deref接口,它基本上允許您直接調用Rc指向的值(在您的情況下為List枚舉)的方法。

看到這個還有這個更多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM