Explain Rust code

Paste Rust and Vibe explains what each borrow allows, what a lifetime ties together and why the compiler accepts or rejects it.

stock.rs

Up to 1,500 characters (about 60 lines). Your code is sent to Unvibe and Google Gemini to write the explanation. Don't paste keys or passwords. Common key formats are refused.

Vibe22 lines selected

Press Explain it for the sample, or paste your own code first.

What this Rust sample shows

traits
Available names one method, and impl Available for Stock gives Stock that method. first_available takes a slice of any type T that implements the trait; here that is Stock, and an item with a quantity of 0 doesn't count as available.
lifetimes
'a ties the result to the slice: the &'a T that comes back points at the item inside items itself, not at a copy. Rust would infer the same lifetimes here: a version without 'a compiles too, because only one reference goes in.
borrowing
first_available takes &[T], a shared borrow, and reserve takes &mut Stock, a mutable one. While the item first_available(&items) returned is still in use, reserve(&mut items[0]) doesn't compile: rustc stops with error E0502, cannot borrow items as mutable because it is also borrowed as immutable.

Good to know

  • With an empty item first, then box (quantity 2) and bag (quantity 1), first_available skips the empty one and returns box.
  • reserve returns true twice for box, then false, and the quantity stays at 0. The next first_available call returns bag.
  • find gives None for an empty slice or when nothing is available, so the caller has to handle the Option before it can read sku.

Watch out: The if stock.quantity == 0 check matters because quantity is a u32, which can't go below 0. Without it, stock.quantity -= 1 on 0 panics with attempt to subtract with overflow in a debug build, and in a build with -O, where overflow checks are off by default, it quietly wraps to 4294967295.

Explain Rust code beside your editor

Unvibe is a free app for Mac and Windows. In the app there is no pasting: select code in any app and press Control+U (Ctrl+Alt+U on Windows).