# Unwrapping a Result

Many functions in Rust have their return values wrapped in a [`result`](https://doc.rust-lang.org/1.39.0/std/result/index.html). The `Result` type is an enum with two variants, `Ok` and `Err`.

```rust
let result = std::fs::read_to_string("test.txt");
```

It is common to have to handle these cases separately. One can use a `match` statement, like so:

```rust
let content = match result {
  Ok(content) => content,
  Err(error) => panic!("Can't deal with: {}", error),
};
```

but this is in fact so common that there is a shortcut method called `unwrap`:

```rust
let content = result.unwrap();
```

## Returning and the question mark

If we don't want to panic (and exit), we can return an error instead:

```rust
let content = match result {
  Ok(content) => content,
  Err(error) => return Err(error.into()),
};
```

Just like calling `.unwrap()` on a `Result` is a shortcut for `match` with `panic!` in the error arm, `?` is a shortcut for a `match` with a `return` in the error arm:

```rust
let content = result?;
```

### Sources

* [Unwrapping](https://rust-cli.github.io/book/tutorial/errors.html#unwrapping)
* [Question mark](https://rust-cli.github.io/book/tutorial/errors.html#question-mark)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.eliasnorrby.com/rust/unwrapping.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
