Channel Directions in Rust
In Rust, we can specify whether a channel is for sending or receiving values when using them as function parameters. This specificity increases the type-safety of the program.
To run the program:
In this Rust version, we use the std::sync::mpsc
module to create channels. The Sender
and Receiver
types are used to specify the direction of the channel.
The ping
function takes a &Sender<String>
, which can only send values. The pong
function takes a &Receiver<String>
for receiving and a &Sender<String>
for sending.
In the main
function, we create two channels using mpsc::channel()
. We then pass the appropriate senders and receivers to our functions.
This approach ensures type safety at compile-time, preventing misuse of the channels.