Rust patterns for C programmers
Result and ?, Option, enums as state machines, type-state and calling C.
Reading Rust as a C programmer
The Rust for embedded lesson explains ownership and borrowing. This one covers the everyday patterns you meet when you read embedded Rust, each next to the C you would write today. Rust code here is for reading; the C examples run.
Errors: Result and the ? operator
C returns a status and passes the result through a pointer, and nothing forces the caller to check it. Rust returns one value that is either the result or an error, and the compiler refuses to let you use the result without handling the error case:
#[derive(Debug)]
enum SensorError { Timeout, Crc, Range }
fn read_celsius(bus: &mut I2c) -> Result<i16, SensorError> {
let raw = read_register(bus, 0x00)?; // on Err, return it to our caller right here
check_crc(&raw)?;
let c = convert(raw);
if c < -40 || c > 125 { return Err(SensorError::Range); }
Ok(c)
}
match read_celsius(&mut bus) {
Ok(c) => display(c),
Err(SensorError::Timeout) => retry_later(),
Err(e) => log_error(e),
}
The ? operator replaces the C idiom of checking and returning the error on every line:
#include <stdio.h>
#include <stdint.h>
typedef enum { ERR_OK, ERR_TIMEOUT, ERR_CRC, ERR_RANGE } err_t;
static err_t read_register(uint16_t *raw) { *raw = 0x0190; return ERR_OK; }
static err_t check_crc(uint16_t raw) { (void)raw; return ERR_OK; }
/* Every call needs the same three lines; forgetting one is a silent bug. */
static err_t read_celsius(int16_t *out) {
uint16_t raw;
err_t e = read_register(&raw);
if (e != ERR_OK) return e;
e = check_crc(raw);
if (e != ERR_OK) return e;
int16_t c = (int16_t)(raw / 16);
if (c < -40 || c > 125) return ERR_RANGE;
*out = c;
return ERR_OK;
}
int main(void) {
int16_t c;
if (read_celsius(&c) == ERR_OK) printf("%d C\n", c);
read_celsius(&c); /* compiles fine in C, even though the error is ignored */
return 0;
}
In Rust, ignoring a Result is a compiler warning, and using the value inside it without handling the error is impossible.
Option instead of NULL and magic values
Where C returns NULL, -1 or INT16_MIN to mean "nothing", Rust returns Option<T>: Some(value) or None. A function that may not find anything says so in its type, and the caller must deal with None before getting at the value:
fn find_free_slot(slots: &[Slot]) -> Option<usize> {
slots.iter().position(|s| s.is_free())
}
if let Some(i) = find_free_slot(&slots) {
slots[i].store(record);
} else {
report_full();
}
Option<&T> costs no extra memory: the compiler uses the null pointer value to mean None, so it is exactly as big as a C pointer, but cannot be dereferenced by mistake.
Enums that carry data: state machines
A Rust enum is a tagged union: each variant can hold its own data, and match must cover every variant or the code does not compile. That makes it the natural shape for a state machine. In C you build the same thing by hand:
#include <stdio.h>
#include <stdint.h>
/* A C tagged union: the tag says which member of the union is valid. */
typedef enum { ST_IDLE, ST_HEATING, ST_FAULT } state_tag_t;
typedef struct {
state_tag_t tag;
union {
struct { int16_t target; } heating; /* only valid when tag == ST_HEATING */
struct { uint8_t code; } fault; /* only valid when tag == ST_FAULT */
} u;
} state_t;
static void describe(state_t s) {
switch (s.tag) {
case ST_IDLE: printf("idle\n"); break;
case ST_HEATING: printf("heating to %d C\n", s.u.heating.target); break;
case ST_FAULT: printf("fault %u\n", s.u.fault.code); break;
/* Add a state and forget it here: the compiler at best warns. */
}
}
int main(void) {
state_t s = { .tag = ST_HEATING, .u.heating = { 60 } };
describe(s);
s.tag = ST_FAULT; /* oops: the union still holds the heating data */
describe(s); /* reads 60 as a fault code */
return 0;
}
The Rust version cannot make that mistake, because the data lives inside the variant and is only reachable by matching on it:
enum State {
Idle,
Heating { target: i16 },
Fault { code: u8 },
}
fn describe(s: &State) {
match s {
State::Idle => println!("idle"),
State::Heating { target } => println!("heating to {} C", target),
State::Fault { code } => println!("fault {}", code),
} // add a variant and every match that misses it is a compile error
}
Type-state: invalid operations do not compile
Rust can encode a peripheral's configuration in its type, so using it wrongly is a compile error rather than a runtime bug. HAL crates do this for pins:
let pin = gpioa.pa5; // type: PA5<Input<Floating>>
let mut led = pin.into_push_pull_output(); // consumes the input, returns PA5<Output<PushPull>>
led.set_high(); // fine
// pin.set_high(); // error: `pin` was moved, and inputs have no set_high
The conversion consumes the old value, so there is no stale handle that still thinks the pin is an input. The types exist only at compile time: the generated code is the same register writes as C.
Calling C from Rust, and Rust from C
Real products mix both. Vendor HALs, RTOSes and stacks stay in C, and new modules can be written in Rust.
#[repr(C)] // lay the struct out exactly as C would
pub struct Reading { pub millivolts: u16, pub channel: u8 }
extern "C" {
fn hal_adc_read(channel: u8) -> u16; // a C function from the vendor HAL
}
#[no_mangle] // keep the symbol name so C can call it
pub extern "C" fn filter_update(sample: u16) -> u16 {
let raw = unsafe { hal_adc_read(0) }; // calling C is unsafe: Rust cannot check it
(sample + raw) / 2
}
bindgen generates these declarations from C headers, and cbindgen generates C headers from Rust. The boundary is where Rust's guarantees stop, so it is kept narrow and wrapped in safe Rust functions.
Pitfall:
unwrap()on aNoneorErrpanics, and on a microcontroller a panic usually halts or resets the device. It is fine in examples and at start-up for things that cannot fail, but production paths should handle the error.
Interview question: How would you introduce Rust into an existing C firmware project?
Answer: Gradually, at a clear boundary. I would pick a self-contained module with a simple interface and high bug risk, such as a protocol parser that handles untrusted input, write it in Rust as a static library with a C-compatible API using repr(C) types and extern "C" functions, and generate the header with cbindgen. The C build links the library. Calls into existing C code go through bindgen declarations wrapped in safe functions. The team needs time to learn, the toolchain and debugger setup must be part of CI, and certification requirements, if any, need checking first.
Going deeper
Interview question: How would a C firmware team introduce Rust without rewriting everything?
Answer: Start with a self-contained module (a parser, a protocol) in Rust behind a C interface, so the build and the debugging workflow can be proven. Map familiar C patterns to Rust ones (registers via PACs, ISRs with critical-section shared state, static buffers), add CI for both languages, and grow from there.
Interview question: Why does Option<&T> take no more memory than a pointer?
Answer: A Rust reference can never be null, so the null value is free to use as the representation of None; this is called the null pointer optimisation. Option<&T> is therefore exactly one pointer wide and, at the machine level, the same as a nullable C pointer, but the type system forces the code to check for None before using the reference. The same optimisation applies to other types with an impossible value, such as NonZeroU32.
Interview question: What does type-state mean, and what does it cost at run time?
Answer: Type-state encodes the state of an object, such as a pin being an input or an output, or a peripheral being enabled, in its type, and makes the methods that change state consume the old value and return a new type. Calling a method that is invalid in the current state is then a compile error. The types are erased during compilation, usually as zero-sized marker types, so there is no run-time cost: the generated code is the same register access you would write in C.
Explain it: In your own words, explain how a Rust enum with match prevents bugs that a C tagged union allows.
Answer: In C, a tagged union keeps the tag and the data separate, so nothing stops code from changing the tag without changing the data, or reading the wrong member of the union. A switch that misses a case still compiles. In Rust, each enum variant holds its own data, and the only way to reach that data is to match on the variant, so you can never read the heating target while in the fault state. match must also cover every variant, so adding a new state makes the compiler point at every place that needs to handle it.