Challenge - 5 Problems
Rust Copy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of copying a simple type
What is the output of this Rust code snippet?
Rust
fn main() {
let x = 5;
let y = x;
println!("x = {}, y = {}", x, y);
}Attempts:
2 left
💡 Hint
Simple integer types implement the Copy trait, so the value is copied, not moved.
✗ Incorrect
In Rust, integers implement the Copy trait, so assigning x to y copies the value. Both x and y remain valid and equal to 5.
❓ Predict Output
intermediateCopy trait with tuples
What will this Rust program print?
Rust
fn main() {
let a = (10, 20);
let b = a;
println!("a = {:?}, b = {:?}", a, b);
}Attempts:
2 left
💡 Hint
Tuples of Copy types are also Copy.
✗ Incorrect
Since both elements of the tuple are integers (Copy types), the tuple itself implements Copy. So a is copied to b, both remain valid.
❓ Predict Output
advancedCopy trait with custom struct
What is the output of this Rust code?
Rust
#[derive(Debug, Copy, Clone)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = p1;
println!("p1 = {:?}, p2 = {:?}", p1, p2);
}Attempts:
2 left
💡 Hint
The struct derives Copy and Clone, so it can be copied.
✗ Incorrect
The #[derive(Copy, Clone)] attribute allows Point to be copied. Assigning p1 to p2 copies the data, so both remain valid and equal.
❓ Predict Output
advancedCopy trait and references
What will this Rust code print?
Rust
fn main() {
let s = String::from("hello");
let r1 = &s;
let r2 = r1;
println!("r1 = {}, r2 = {}", r1, r2);
}Attempts:
2 left
💡 Hint
References implement Copy, so copying references is allowed.
✗ Incorrect
References (&String) implement Copy, so r1 is copied to r2. Both references point to the same String, so printing both works fine.
❓ Predict Output
expertCopy trait with arrays and slices
What is the output of this Rust program?
Rust
fn main() {
let arr1 = [1, 2, 3];
let arr2 = arr1;
let slice1 = &arr1[..];
let slice2 = slice1;
println!("arr1 = {:?}, arr2 = {:?}", arr1, arr2);
println!("slice1 = {:?}, slice2 = {:?}", slice1, slice2);
}Attempts:
2 left
💡 Hint
Arrays of Copy types implement Copy; slices are references and also Copy.
✗ Incorrect
Arrays of integers implement Copy, so arr1 is copied to arr2. Slices are references and implement Copy, so slice1 is copied to slice2. Both print the same values.
