![](/img/trans.png)
[英]UdpFramed with Actix Rust. Can't send messages using SinkWrite
[英]Rust. Confusion around using functions from impl in global scope
我正在做 Rust 書中的示例,但我不明白這一點。 當tail()在List的實現中是 function 並且a是Rc類型時, 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 的確切自動取消引用規則是什么? 更多細節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.