Home »
Rust »
Rust Programs
Rust program to pass a channel to the function
Rust | Thread Example: Write a program to pass a channel to the function.
Submitted by Nidhi, on November 02, 2021
Problem Solution:
In this program, we will pass a channel to the function and send a message to the main thread and print the received message.
Program/Source Code:
The source code to pass a channel to the function is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
// Rust program to pass a channel
// to the function
use std::thread;
use std::sync::mpsc;
fn fun(chnl: mpsc::Sender<i32>) {
// Send a integer value
chnl.send(786).unwrap();
}
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
// Pass channel as a parameter.
fun(tx);
});
// Receive message from thread.
let val = rx.recv().unwrap();
println!("Message received: {}", val);
}
Output:
$ rustc main.rs
$ ./main
Message received: 786
Explanation:
Here, we created two functions fun() and main(). The fun() function accepts the channel as a parameter and sends the message to the main thread. And, we created a thread and called the fun() function to send a message. Then we received the message using the recv() function and printed the received message.
Rust Threads Programs »