How to avoid unused warning

In this program, I want to use the contents of the file outside the if statement. This code works, but I get the warning "value assigned to contents is never read". How can I change it so I don't get the warning, but keep the functionality?

use std::fs;
use std::io;
fn main() {
    let filename = "example.txt";
    fn read_file_contents(filename: &str) -> Result<String, io::Error> {
        let fcontents = fs::read_to_string(filename)?;
        Ok(fcontents)
    }
    let mut contents = String::new();
    if let Ok(fcontents) = read_file_contents(filename) {
        contents = fcontents;
    } else {
        panic!("Error reading file {}", filename);
    }
    println!("File contents: {}", contents);
}

Just write let contents; -- it doesn't even need to be mut when there's a single assignment, even if that comes later.

3 Likes

Or use let-else syntax instead:

use std::fs;
use std::io;
fn main() {
    let filename = "example.txt";
    fn read_file_contents(filename: &str) -> Result<String, io::Error> {
        let fcontents = fs::read_to_string(filename)?;
        Ok(fcontents)
    }
    let Ok(contents) = read_file_contents(filename) else {
        panic!("Error reading file {}", filename);
    };
    println!("File contents: {}", contents);
}
2 Likes

Thanks very much! I finally choose this option, because I want to have access to the error message as well.

use std::fs;
use std::io;
fn main() {
    let filename = "example.txt";
    fn read_file_contents(filename: &str) -> Result<String, io::Error> {
        let fcontents = fs::read_to_string(filename)?;
        Ok(fcontents)
    }
    let contents;
    match read_file_contents(filename) {
        Ok(fcontents) => {
            contents = fcontents;
        }
        Err(err) => {
            panic!("Failed to read file {}: {}", filename, err);
        }
    }
    println!("File contents: {}", contents);
}

I think you can also move let contents to single line like

let contents = match read_file_contents(filename) {

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.