Answer#
Explaining code is a good use of an assistant: it can name the pattern, walk through the flow and answer "why" questions at your own pace. The weak point is that a confident explanation of a wrong idea reads exactly like a correct one. Pair it with a source that cannot be wrong about the compiler: the compiler.
How to do it#
- Select the lines you do not understand, or leave the selection empty to explain the whole open file. Press Explain. The quick action sends: "Explain what this code does, step by step, and point out anything surprising."
- Ask narrower questions afterwards, in the same chat, since the earlier turns are sent along: "why is
&mutneeded on this line?", "what does?return here?", "what would change if this wereRcinstead ofArc?". - For an error code, ask the compiler for its own explanation.
rustc --explain E0382prints a long description with a small example of the mistake and its fix:
> rustc --explain E0382
A variable was used after its contents have been moved elsewhere.
Erroneous code example:
struct MyStruct { s: u32 }
fn main() { let mut x = MyStruct{ s: 5u32 }; let y = x; x.s = 6; println!("{}", x.s); }
Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
of workarounds like `Rc`, a value cannot be owned by more than one variable.
Sometimes we don't need to move the value. Using a reference, we can let another
function borrow the value without changing its ownership. In the example below,
we don't actually have to move our string to `calculate_length`, we can give it
a reference to it with `&` instead.
...- Ask the assistant to explain the error in terms of your code, then compare. If the two disagree, trust the compiler's text and ask the assistant to reconcile them.
- Test understanding by changing the code. Predict what the compiler will say, make the change, and see if you were right. Rust's messages are detailed enough to learn from.
Common mistakes#
- Asking for an explanation without including the error. The assistant then explains the code in general instead of why it fails.
- Treating the explanation as a source. For a language rule, the official Rust Book and reference are the sources; the assistant is a tutor next to them.
- Asking for a rewrite in the same breath as an explanation. Understand first, then ask for a change.
Related questions#
Does the assistant see my whole project?#
No. It sees the open file or selection if the toggle is on, files named with @, and a short summary. See the thread on what the assistant sends.