📖 Scenario: Imagine you are building a simple text processing tool that needs to handle words and sentences. Different programming languages treat text data differently. In Rust, strings are handled with care to manage memory and safety.
🎯 Goal: You will create a Rust program that shows how to create and manipulate strings using String and string slices (&str), demonstrating the difference between owned and borrowed strings.
📋 What You'll Learn
Create a string slice with a fixed text
Create an owned String from the string slice
Append text to the owned String
Print both the string slice and the owned String
💡 Why This Matters
🌍 Real World
Handling text data safely and efficiently is important in many applications like web servers, text editors, and command-line tools.
💼 Career
Understanding Rust's string types helps you write memory-safe and performant code, a valuable skill for systems programming and backend development.
Progress0 / 4 steps
1
Create a string slice
Create a string slice called greeting with the value "Hello".
DSA Rust
Hint
A string slice is a reference to a string literal, written as &str.
2
Create an owned String from the string slice
Create an owned String called owned_greeting by converting the string slice greeting using to_string().
DSA Rust
Hint
Use to_string() method on the string slice to create an owned String.
3
Append text to the owned String
Append the text ", world!" to the owned String owned_greeting using the push_str() method.
DSA Rust
Hint
Remember to make owned_greeting mutable with mut to append text.
4
Print both the string slice and the owned String
Print the string slice greeting and the owned String owned_greeting on separate lines using println!.
DSA Rust
Hint
Use println!("{}", variable) to print variables.
Practice
(1/5)
1. In Rust, which of the following best describes how String differs from string types in some other languages like Python or JavaScript?
easy
A. String in Rust is immutable and fixed-length like Python strings.
B. String in Rust is a growable, heap-allocated UTF-8 encoded string.
C. String in Rust stores characters as UTF-16 code units internally.
D. String in Rust is a simple alias for a byte array without encoding.
Solution
Step 1: Understand Rust's String type
Rust's String is designed to be growable and stored on the heap, unlike fixed-length strings in some languages.
Step 2: Compare with other languages
Languages like Python have immutable strings, and JavaScript strings are UTF-16 encoded internally, but Rust uses UTF-8 encoding for String.
Final Answer:
String in Rust is a growable, heap-allocated UTF-8 encoded string. -> Option B
Quick Check:
Rust String = growable UTF-8 heap string [OK]
Hint: Remember Rust strings are UTF-8 and growable, unlike fixed immutable strings [OK]
Common Mistakes:
Thinking Rust strings are immutable like Python strings
Assuming Rust strings use UTF-16 encoding
Confusing String with byte arrays without encoding
2. Which of the following is the correct way to create a mutable String in Rust?
easy
A. let mut s = String::from("hello");
B. let s = "hello";
C. let s = String::new("hello");
D. let s = "hello".to_string();
Solution
Step 1: Identify mutable string creation syntax
In Rust, to create a mutable String, you declare it with mut and use String::from or to_string().
Step 2: Check each option
let s = "hello"; creates an immutable string slice (&str), not a String. let mut s = String::from("hello"); correctly creates a mutable String. let s = String::new("hello"); is invalid syntax. let s = "hello".to_string(); creates a String but lacks mut, making the binding immutable.
Final Answer:
let mut s = String::from("hello"); -> Option A
Quick Check:
Mutable String = let mut s = String::from(...) [OK]
Hint: Use let mut s = String::from(...) for mutable strings [OK]
Common Mistakes:
Using string literals without mut for mutability
Trying to use String::new("hello") which is invalid
Confusing string slices with String type
3. What will be the output of the following Rust code?
let s = String::from("hello");
let h = &s[0..1];
println!("{}", h);
medium
A. Runtime panic due to invalid UTF-8 slicing
B. he
C. h
D. hello
Solution
Step 1: Understand Rust string slicing rules
Rust strings are UTF-8 encoded, so slicing must be on valid UTF-8 boundaries. Index 0..1 slices the first byte only.
Step 2: Check if slicing 0..1 is valid UTF-8
For "hello", ASCII characters are 1 byte each, so 0..1 is valid and equals "h".
Step 3: Confirm output
println!("{}", h) where h = &s[0..1] = "h" outputs h.
Final Answer:
h -> Option C
Quick Check:
Slice 0..1 of "hello" = "h" [OK]
Hint: Remember ASCII chars are 1 byte, so 0..1 slice is valid [OK]
Common Mistakes:
Assuming slicing 0..1 causes panic always
Confusing byte index with character index
Expecting multiple characters from 0..1 slice
4. Identify the error in this Rust code snippet:
let s = String::from("Здравствуйте");
let slice = &s[0..1];
println!("{}", slice);
medium
A. No error, prints first character
B. Prints garbage characters
C. Compile-time error: invalid slice syntax
D. Runtime panic: slicing not on UTF-8 boundary
Solution
Step 1: Analyze the string content and slicing
The string "Здравствуйте" contains Cyrillic characters, each encoded in multiple bytes in UTF-8.
Step 2: Check slicing 0..1 validity
Slicing 0..1 takes only the first byte, which is not a valid UTF-8 character boundary for Cyrillic letters, causing a runtime panic.
Final Answer:
Runtime panic: slicing not on UTF-8 boundary -> Option D
Using for i in 0..s.len() and slicing &s[i..i+1] slices bytes which can cause invalid UTF-8. for c in s.bytes() iterates bytes, not characters. for c in s.split(' ') splits by spaces, not characters.
Final Answer:
Using for c in s.chars() to iterate over Unicode scalar values. -> Option A
Quick Check:
Use s.chars() for safe Unicode iteration [OK]
Hint: Use s.chars() to safely iterate Unicode characters [OK]
Common Mistakes:
Iterating bytes instead of characters
Slicing string by byte indices unsafely
Using split which divides by delimiter, not characters
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.