Data, absence and errors · 13 min · free lesson

NULL and errno to Option and Result

Absence is Option<T> and failure is Result<T, E>, both in the return type, so a caller cannot use the value without handling the other case.

Core idea

Return Option<T> when a value may simply be absent and Result<T, E> when the caller needs to know why an operation failed.

C and Rust, side by side

C -1 is both the failure marker and a valid result, so the caller must clear and inspect errno; getenv returns NULL when the variable is absent.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

/* Returns -1 and sets errno on failure. But "-1" is also a valid input. */
static long parse_count(const char *text) {
    char *end;
    errno = 0;                       /* strtol sets errno only on failure */
    long value = strtol(text, &end, 10);
    if (end == text || *end != '\0') {
        errno = EINVAL;
        return -1;
    }
    return value;                    /* on ERANGE: LONG_MAX or LONG_MIN */
}

int main(void) {
    long ok = parse_count("42");
    long bad = parse_count("4x");
    int bad_errno = errno;
    long minus = parse_count("-1");  /* the same -1, with errno == 0 */
    printf("%ld %ld(errno=%d) %ld(errno=%d)\n", ok, bad, bad_errno, minus, errno);
    const char *dir = getenv("CRABRIX_EXAMPLE_UNSET"); /* NULL when absent */
    printf("%s\n", dir ? dir : "(not set)");            /* forget the check: crash */
    return 0;
}
Rust parse_count returns its error as a value, -1 parses as Ok(-1), an unset variable is None, and ? passes the first failure up.
use std::num::ParseIntError;

fn parse_count(text: &str) -> Result<i64, ParseIntError> {
    text.parse::<i64>() // the error is the return value, not a global
}

fn sum_counts(a: &str, b: &str) -> Result<i64, ParseIntError> {
    Ok(parse_count(a)? + parse_count(b)?) // `?` returns the first error
}

fn main() {
    println!("{:?}", parse_count("42"));
    println!("{:?}", parse_count("4x"));
    println!("{:?}", parse_count("-1")); // Ok(-1): no confusion with failure
    match std::env::var_os("CRABRIX_EXAMPLE_UNSET") {
        Some(dir) => println!("{dir:?}"),
        None => println!("(not set)"), // absence must be handled
    }
    println!("{:?} {:?}", sum_counts("40", "2"), sum_counts("40", "x"));
}
What changes
CRust
NULL means absent, and dereferencing it unchecked compiles.Option<T> must be matched before the value can be used.
-1 plus errno signals failure out of band.Result<T, E> carries the reason in the return value.
if (rc < 0) return rc; after every call.? returns the error early and unwraps the success value.

Understand it

C signals trouble out of band. A pointer return uses NULL for absent, as getenv and strchr do. An integer return reserves a value such as -1 and leaves the reason in errno, which must be cleared before calls such as strtol and read before the next library call can overwrite it. In the example, -1 means failure and is also a valid parsed value, so the caller has to inspect errno to tell them apart.

Rust puts both into the type. Option<T> is Some(value) or None; Result<T, E> is Ok(value) or Err(error). You cannot use the T inside without saying what happens in the other case: let port: u16 = find_port(&config); is error E0308, because the function returns Option<u16>. References are never null, so Option<&T> is the nullable pointer, with the same size as a plain reference.

Choose by what the caller needs. A lookup that may find nothing returns Option. Parsing external text, I/O and anything with several distinct causes of failure return Result with an error type that names them, often an enum such as PortError. The ? operator replaces the if (rc < 0) return rc; ladder: it returns the error to the caller and unwraps the success value.

unwrap() and expect(...) turn None or Err into a panic. They belong in tests, examples and states that are truly impossible; for expected failures such as invalid input, return the Result. Unlike errno, an error value cannot be overwritten by a later call, and it travels with the result it describes.

The C habit, written in Rust

This is how the C version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

fn find_port(config: &[(&str, u16)]) -> Option<u16> {
    config.iter().find(|(key, _)| *key == "port").map(|(_, value)| *value)
}

fn main() {
    let config = [("host", 80)];
    let port: u16 = find_port(&config);
    println!("{}", port + 1);
}

Practise this code in Playground ↗

Try it

Port the commented C parse_port: return Empty for empty text, NotANumber if any character is not an ASCII digit (no sign and no spaces, stricter than strtol), OutOfRange for 0 or anything above 65535, and the port otherwise.

What success looks like: "8080" parses, "+80" is NotANumber, and "0", "65536" and a 20-digit number are OutOfRange.

Check your understanding

A C lookup returns NULL when a key is missing, and a config parser returns -1 with errno set when a line is malformed. Which Rust return types fit those two cases?

Reveal the answer
  1. Result<T, ()> for both
  2. Option<T> for both, with None for any problem
  3. *const V for the lookup and i32 plus a global error code for the parser
  4. Option<&V> for the lookup and Result<Config, ParseError> for the parser

A missing key is ordinary absence. A malformed line is a failure the caller should be able to explain or report, so it carries an error value.

Go deeper

Common misconception: “unwrap() is the Rust way to read a return value.”

unwrap() turns an absent value or an error into a panic. Use it where failure would be a bug; for input that can be invalid, match on the Result or return it with ?.

  1. Classify each failure: For each C return code or NULL, decide whether it is absence (Option) or a failure with a reason (Result).
  2. Name the reasons: Turn the errno values a function can set into the variants of an error enum.
  3. Propagate with ?: Replace each check-and-return ladder with ? inside a function that returns Result.

Transfer challenge: Write fn parse_endpoint(text: &str) -> Result<(String, u16), EndpointError> for host:port that reuses parse_port with ? through a From<PortError> conversion.

Connections

  • Tagged Unions to Enums: A tag that cannot disagree with its payload
  • char Arrays to Strings: Owned UTF-8 with a length, not a NUL
Side-by-side comparison: the C version on the left, the Rust version on the right, then 3 rows naming what changes.
NULL and errno to Option and Result: the same task in C and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: NULL and errno to Option and Result (courseId "rust-for-c-developers", lessonId "c-null-and-errno-to-option-result")
Link: https://crabrix.com/learn/rust-for-c-developers/c-null-and-errno-to-option-result/
Goal: Return Option<T> when a value may simply be absent and Result<T, E> when the caller needs to know why an operation failed.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-null-and-errno-to-option-result) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.