Executing the following code results in:
error[E0381]: borrow of possibly-uninitialized variable: nic
use std::io::Error;
fn main() {
// let nic = get_network_interface_connection().unwrap(); //This works but I want explicit error handling
let nic;
match get_network_interface_connection() {
Ok(new_nic) => nic = new_nic,
Err(e) => println!("{:?}", e),
}
let mut buf = [0u8; 1504];
// PROBLEM HERE!! In next line... error[E0381]: borrow of possibly-uninitialized variable: `nic`
let nbytes = nic.recv(&mut buf[..]); // PROBLEM HERE!! error[E0381]: borrow of possibly-uninitialized variable: `nic`
}
fn get_network_interface_connection() -> Result<tun_tap::Iface, Error> {
let new_nic = tun_tap::Iface::new("tun0", tun_tap::Mode::Tun)?; //Network Interface Connection(nic)
Ok(new_nic)
}
I understand if the match errors out then nic variable will never be initialized; so I tried to find a way to initialize the nic var in error clause, but couldn't.
I want to know how I can initialize nic if error happens to avoid error[E0381]........or if this is even the right concept to apply here.
The "let nbytes = ..." line will eventually be in a loop to receive packets via TCP.
Just to add a little bit to the answer. You rarely need to or want to declare a variable ahead of time like let nic; in rust. In a situation like yours, you'll typically either use a match statement as above or use the ? operator as you did you in your function which will early return any errors and extract a successful function call. In your case, since the variable was declared in main without a return type, the ? operator can't be used.