Borrow Results For Inspection With as_ref

Inspect a Result without consuming it: as_ref turns Result<T, E> into Result<&T, &E> so the check can branch on contents and still hand the value onward.

RustData Integrity

Code

rustsnippet
19 lines
fn classify(batch: Result<Vec<u32>, String>) -> (String, Result<Vec<u32>, String>) {
    // as_ref 把 Result<T, E> 变成 Result<&T, &E>:先借用检查,原值原封不动
    let note = match batch.as_ref() {
        Ok(items) if items.len() > 3 => format!("large batch: {} items", items.len()),
        Ok(items) => format!("small batch: {} items", items.len()),
        Err(e) => format!("rejected: {e}"),
    };
    (note, batch) // batch 未被消耗,继续向下传递
}

fn main() {
    let ok = classify(Ok(vec![1, 2, 3, 4, 5]));
    println!("{}", ok.0);
    println!("still usable: {:?}", ok.1.as_ref().unwrap().len());

    let bad = classify(Err(String::from("checksum mismatch")));
    println!("{}", bad.0);
    println!("error kept: {:?}", bad.1.as_ref().unwrap_err());
}

Borrowing the Result without consuming it

classify(batch) needs the contents for a note but must return the original Result untouched, so the match runs on batch.as_ref() — which turns Result<Vec<u32>, String> into Result<&Vec<u32>, &String>. The arms read through the reference: Ok(items) if items.len() > 3 produces large batch: {} items, the plain Ok(items) arm produces small batch: {} items, and Err(e) produces rejected: {e}. The tuple (note, batch) then moves the unconsumed value onward — the comment marks exactly that guarantee.

What the two demo calls print

large batch: 5 items
still usable: 5
rejected: checksum mismatch
error kept: "checksum mismatch"

The first call passes Ok(vec![1, 2, 3, 4, 5]); the returned ok.1 is still an owned Result, so ok.1.as_ref().unwrap().len() reads 5 through another borrow. The second call passes an Err, and bad.1.as_ref().unwrap_err() borrows the payload — the {:?} format adds the quotes around "checksum mismatch" in the last line.

The line that keeps ownership

(note, batch) // batch 未被消耗,继续向下传递

Without as_ref, the match on batch would move it and this return would be a borrow error — the single method call is what lets inspection and forwarding coexist.

Interactive Tools for This Topic

FAQ

How should callers handle failures?
No panics — `Result` values carry the failure.
What does Borrow Results For Inspection With as_ref print when run?
No setup needed: run the file and look for labeled lines like `still usable:`, `error kept:` in the output.