I am trying to write a function that reads file content and return relevant data vector, but I am not sure how to return the error when the input file name is not found.
Not sure if the below code expression is correct, but I hope someone can make out, as I do not know how to handle error returning
pub fn func2_read_file(max_line:usize) -> Result<Vec<DataStruct>, io::Error>{
let file = File::open(filename).unwrap(); // Ignore errors.
let reader = BufReader::new(file);
let mut vec_data:Vec<DataStruct>=Vec::new();
for (index, line) in reader.lines().enumerate() {
let line = line.unwrap(); // Ignore errors.
let split = line.split("\t");
let vec = split.collect::<Vec<&str>>();
vec_data.push(DataStruct {
id: vec[0].parse::<i32>().unwrap(), // Ignore errors.
name_acsii: vec[2].to_string(),
latitude: vec[4].parse::<f32>().unwrap(), // Ignore errors.
longitude: vec[5].parse::<f32>().unwrap(), // Ignore errors.
});
if index>max_line{
break;
}
}
return vec_data; // Definitely not going to work here
}
So, as you can see, the code above use a lot of .unwrap(), which I assume lots of error has been ignored.
In Go, I can just have each error return as Null or various string, for various error.
I don't even know what type of Error Rust has. I just put io::Error because it's related to file reading, but obviously there are other errors, like convert the string to f32. I want to catch the error in other functions, and handle it accordingly.
So anyway, like in the above code for example, what is the rust way to return properly, and maybe catch the error in main function, as I am new to Rust so I am not 100% sure of what I am doing. I know, to return error, there are some long route and short route, but since I am still learning, I would prefer the long error returning method to understand everything clearly.
Or if I am doing something in a not-very-rust way, please enlighten me.
Thank you