rustbeginner
Rust Basics
Ownership, borrowing and basic syntax
6 questions
By EZ4Code Team
1. What is the keyword to declare an immutable variable in Rust?
let
const let
var
immutable
Explanation: let declares a variable, which is immutable by default; let mut declares a mutable variable; const declares a compile-time constant.
2. Can the following code compile? let s1 = String::from("hi"); let s2 = s1; println!("{}", s1);
let s1 = String::from("hi");
let s2 = s1;
println!("{}", s1);No: ownership of s1 has been moved to s2, s1 can no longer be used
Yes: outputs hi
Yes: outputs empty
Yes: throws a runtime error
Explanation: String does not implement Copy; after assignment to s2, ownership moves and s1 becomes invalid. Using s1 again causes a compile error.
3. What are the rules of borrowing?
At any time you can have either multiple immutable borrows, or one mutable borrow; the two cannot coexist
You can have both mutable and immutable borrows at the same time
You can only have one immutable borrow
Borrowing has no restrictions
Explanation: Rust borrowing rules: any number of immutable references &T, or exactly one mutable reference &mut T; the two are mutually exclusive, ensuring memory safety.
4. Which of the following types implements the Copy trait?
Primitive integer types like i32
String
Vec<T>
Box<T>
Explanation: Types that implement Copy (such as i32, f64, bool, &T) are copied bitwise on assignment, with no ownership transfer; String/Vec/Box are heap-allocated and do not implement Copy.
5. When passing a String to a function, what happens by default?
Ownership is moved into the function
It is automatically copied
It is automatically borrowed
It is passed by reference
Explanation: Pass-by-value by default causes ownership transfer; if you only want to borrow, explicitly pass &s or &mut s.
6. What are the characteristics of a match expression?
It must be exhaustive over all possibilities, and each arm must return the same type
It does not need to be exhaustive
It does not need a return value
It can only match integers
Explanation: match must cover all patterns (you can use _ as a wildcard); the types of all arm expressions must be consistent. It is an expression, not a statement.