Challenge - 5 Problems
Rust String Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust string slicing code?
Consider the following Rust code that slices a string. What will be printed?
DSA Rust
fn main() {
let s = String::from("hello");
let slice = &s[0..2];
println!("{}", slice);
}Attempts:
2 left
💡 Hint
Remember Rust string slices use byte indices and must be on valid UTF-8 boundaries.
✗ Incorrect
The slice &s[0..2] takes the first two bytes of the string "hello", which correspond to the characters 'h' and 'e'. So it prints "he".
❓ Predict Output
intermediateWhat happens when slicing a UTF-8 string incorrectly in Rust?
What error or output results from this Rust code?
DSA Rust
fn main() {
let s = String::from("Здравствуйте");
let slice = &s[0..1];
println!("{}", slice);
}Attempts:
2 left
💡 Hint
UTF-8 characters can be multiple bytes; slicing must respect character boundaries.
✗ Incorrect
The character "З" is 2 bytes in UTF-8. Slicing only the first byte causes a runtime panic because it breaks UTF-8 encoding rules.
🔧 Debug
advancedWhy does this Rust code fail to compile when concatenating strings?
Identify the error in this Rust code and what causes it.
DSA Rust
fn main() {
let s1 = String::from("Hello, ");
let s2 = "world!";
let s3 = s1 + s2;
println!("{}", s3);
println!("{}", s1);
}Attempts:
2 left
💡 Hint
The + operator moves the left String operand in Rust.
✗ Incorrect
The + operator takes ownership of s1, so s1 cannot be used after concatenation. The second println! causes a compile error.
❓ Predict Output
advancedWhat is the output of this Rust code using String::from_utf8_lossy?
What does this Rust code print?
DSA Rust
fn main() {
let bytes = vec![240, 159, 146, 150, 255];
let s = String::from_utf8_lossy(&bytes);
println!("{}", s);
}Attempts:
2 left
💡 Hint
from_utf8_lossy replaces invalid bytes with replacement character �.
✗ Incorrect
The bytes represent a valid UTF-8 heart emoji followed by an invalid byte 255, replaced by �.
🧠 Conceptual
expertWhy does Rust differentiate between String and &str types?
Choose the best explanation for why Rust has both String and &str types.
Attempts:
2 left
💡 Hint
Think about ownership and mutability in Rust.
✗ Incorrect
String owns its heap-allocated data and can be changed; &str is a borrowed reference to string data and is usually immutable.
