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.
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
Availablenames one method, andimpl Available for StockgivesStockthat method.first_availabletakes a slice of any typeTthat implements the trait; here that isStock, and an item with a quantity of 0 doesn't count as available.- lifetimes
'aties the result to the slice: the&'a Tthat comes back points at the item insideitemsitself, not at a copy. Rust would infer the same lifetimes here: a version without'acompiles too, because only one reference goes in.- borrowing
first_availabletakes&[T], a shared borrow, andreservetakes&mut Stock, a mutable one. While the itemfirst_available(&items)returned is still in use,reserve(&mut items[0])doesn't compile: rustc stops with errorE0502, cannot borrowitemsas mutable because it is also borrowed as immutable.
Good to know
- With an empty item first, then
box(quantity 2) andbag(quantity 1),first_availableskips the empty one and returnsbox. reservereturnstruetwice forbox, thenfalse, and the quantity stays at 0. The nextfirst_availablecall returnsbag.findgivesNonefor an empty slice or when nothing is available, so the caller has to handle theOptionbefore it can readsku.
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).