I have a piece of code that reads a file using read_to_end
like:
match File::open(file_name) {
Err(err) => "boo hoo".to_string(),
Ok(mut f) => {
let mut bytes:Vec<u8> = Vec::new();
match f.read_to_end(&mut bytes) {
Err(err) => "boo hoo".to_string(),
Ok(_) => "Ha ha".to_string(),
},
},
At the end of the match statement match f.read_to_end(&mut bytes)
the compiler error:
},
| ^ expected expression
But both legs of the match are returning a String
.
Below is a complete programme that illustrates the error followed by th eerror followed by a programme that is subtly different but runs as expected
use std::fs::File;
use std::io::Read;
fn main() {
let file_name = "/tmp/test.txt";
let test_value =
match File::open(file_name) {
Err(err) => "boo hoo".to_string(),
Ok(mut f) => {
let mut bytes:Vec<u8> = Vec::new();
match f.read_to_end(&mut bytes) {
Err(err) => "boo hoo".to_string(),
Ok(_) => "Ha ha".to_string(),
},
},
};
println!("Got string: {}", test_value);
}
Error:
error: expected expression, found `,`
--> src/main.rs:13:18
|
13 | },
| ^ expected expression
error[E0308]: mismatched types
--> src/main.rs:10:17
|
10 | / match f.read_to_end(&mut bytes) {
11 | | Err(err) => "boo hoo".to_string(),
12 | | Ok(_) => "Ha ha".to_string(),
13 | | },
| |_________________^ expected (), found struct `std::string::String`
|
= note: expected type `()`
found type `std::string::String`
Programme that runs:
use std::fs::File;
use std::io::Read;
fn main() {
let file_name = "/tmp/test.txt";
let mut bytes:Vec<u8> = Vec::new();
let test_value =
match File::open(file_name) {
Err(_) => "boo hoo".to_string(),
Ok(mut f) =>
match f.read_to_end(&mut bytes) {
Err(_) => "boo hoo".to_string(),
Ok(_) => "Ha ha".to_string(),
},
};
println!("Got string: {}", test_value);
}
I am missing something here.... (More than the unused err
variables!)