gpt4 book ai didi

rust - 这两种为 Rust channel 克隆发送者的方式有什么区别?

转载 作者:行者123 更新时间:2023-12-03 11:32:31 26 4
gpt4 key购买 nike

在 Rust 官方书籍 16-11 中,它复制了一个 channel 发送器

let (tx, rx) = mpsc::channel();
let tx1 = mpsc::Sender::clone(&tx);

但我试过了

let (tx, rx) = mpsc::channel();
let tx1 = tx.clone();

这也有效。它们之间有什么区别?如果它们本质上相同,考虑到我们已经有了通用的 clone() 方法,为什么要创建一个单独的方法?

最佳答案

clone 的函数签名如下所示。请注意,它将 &self 作为参数:

fn clone(&self) -> Sender<T>;

您可以通过显式传递 &self 来调用该函数:

mpsc::Sender::clone(&tx);

或者使用 method call expression :

tx.clone();

方法调用表达式只是语法糖,尽管编译器必须执行更复杂的查找过程才能为 self 生成正确的引用类型。

请注意,这适用于任何其他采用 self 的关联方法:

pub struct Bar {}

impl Bar {
fn bla(&self) {}
}

fn main() {
let bar = Bar {};

// these are equivalent
bar.bla();
Bar::bla(&bar)
}

关于rust - 这两种为 Rust channel 克隆发送者的方式有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65024989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com