CLetter
CLetter

Reputation: 1

No method named `write` found for enum `Result`

I'm trying to port a C program to Rust. In C I have this statement.

bytes = write(filedevice, cmd, (ssize_t)LEN_SET_ADDRESS_AREA);

I tried to write it like this, but the compiler gives an error saying no method named `write` found for enum `Result` in the current scope . How can I fix this code without using unsafe Rust?

let path = Path::new(DEVICE);
let memory = vec![0; DIM_MEM];
let mut filedevice = File::create(_path);
let file_wr = fildevice.write(&_memory[0]);

Upvotes: 0

Views: 1251

Answers (1)

kotatsuyaki
kotatsuyaki

Reputation: 1641

std::fs::File::create() returns a Result<File>, so you have to do the error handling before accessing the inner File object. A quick and dirty way is to call std::result::Result::unwrap() to unwrap the return value.

let mut file = File::create(path).unwrap();
file.write(buffer);

Note that this causes the program to panic if the Result<File> return value is an error. Read the error handling chapter of the Rust book or the module-level documentation for std::result for other ways to handle the error properly. Here are some examples:

Using .expect()

This provides the ability to print customized error messages.

let mut file = File::create(path).expect("Failed to create file");
file.write(buffer);

Using match

As Result<T, E> is a enum type, we can use a match expression to perform pattern matching, and handle either cases in separate branches.

let mut file = match File::create(path) {
    Ok(file) => file,
    Err(error) => {
        // panic, or you may also want to handle it in other ways
        panic!("Problem creating file: {:?}", error);
    }
};
file.write(buffer);

Upvotes: 2

Related Questions