【问题标题】:What's the differences between these two ways of cloning a sender for a Rust channel?这两种克隆 Rust 通道的发送者的方法有什么区别?
【发布时间】:2021-03-09 12:10:52
【问题描述】:

在 Rust 官方书籍 16-11 中,它复制了一个通道发送者

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

但我试过了

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

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

【问题讨论】:

    标签: rust duplicates clone channel


    【解决方案1】:

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

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

    您可以通过显式传递&amp;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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-08
      • 2019-03-31
      • 1970-01-01
      • 2020-02-14
      • 2011-01-10
      • 2016-07-01
      • 2013-08-08
      相关资源
      最近更新 更多