For future questions, be aware that when you encounter an error and want to ask about it, it’s generally good and useful practice to include the error message you got with the question. It’s also useful to include complete and reproducable code examples in case that’s easily possible, for example if your code wasn’t all that long anyways, or it’s easy to isolate the problem you have to a small self-contained section of code (without changing or leaving out anything that’s relevant for the problem).
Unless you thought that write_mem
’s return type needs not be specified, in which case @leob already provided the perfect answer… perhaps you simply mis-read the precise wording here? It doesn’t say
The operator '?' can only be used on a function that returns Result or Option
but
The operator '?' can only be used in a function that returns Result or Option
Well, the former is actually true as well, but that’s not what the error is referring to, not the return type of File::create
, which would be the return type of the function that ?
is used on, but the return type of the containing function you’re currently defining, write_mem
, is relevant.
This is for the simple reason of what ?
does. A (simplified) desugaring of
let file_buffer = File::create(path_dev)?;
looks like
let file_buffer = match File::create(path_def) {
Ok(value) => value,
Err(error) => return Err(error.into()),
};
For the match
to work, File::create
needs to return Result
, but for the return Error(error)
to work, the function we’re currently in needs to return a Result
, too.