What's the differences between these two ways of cloning a sender for a Rust channel?

Viewed 373

In the Rust official book 16-11, it duplicates a channel sender by

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

But I tried

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

which also works. What's the differences between them? If they are essentially the same, why creating a separate method considering we already have the general clone() method?

1 Answers

The function signature for clone looks like this. Note that it takes &self as a parameter:

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

You can either invoke the function by explicitly passing &self:

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

Or by using a method call expression:

tx.clone();

Method call expressions are just syntactic sugar, although the compiler does has to perform a more complex lookup process to generate the correct reference type for self.

Note that this works with any other associated method that takes self:

pub struct Bar {}

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

fn main() {
    let bar = Bar {};
    
    // these are equivalent
    bar.bla();
    Bar::bla(&bar)
}
Related