Rust, postfix “?”

Let’s assume we have a function such as and we have the line highlight ending in a “?” – what’s this doing?

fn get_history() -> Result<Vec<Revision>, String> {
   let revisions: Vec<Revision> = get_revisions()?;
   return Ok(revisions)
}

We can see that the return is a Result – which is an enum that essentially looks like this

enum Result<T, E> {
    Ok(T),
    Err(E),
}

Hence our get_history function can return a Vec<Revision> which might me Ok (for success ofcourse) or an Err (for an error).

Okay, so what’s the highlighted code doing, especially as we only appear to return an Ok?

This is essentially is the same as the following

let revisions = match get_revisions() {
  Ok(val) => val,
  Err(e) => return Err(e)
};

As we can see this is a nice bit of semantic sugar to return an error from the function OR assign the Ok result to the revisions variable.