Skip to content

Commit

Permalink
09 String slice &str & owned String
Browse files Browse the repository at this point in the history
  • Loading branch information
chiffonng committed Jun 21, 2024
1 parent 907da86 commit 151d372
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 23 deletions.
19 changes: 19 additions & 0 deletions exercises/09_strings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,25 @@ Rust has two string types, a string slice (`&str`) and an owned string (`String`
We're not going to dictate when you should use which one, but we'll show you how
to identify and create them, as well as use them.

## String slice VS owned string

In Rust, understanding the difference between `String` and string slices (`&str`) is crucial for managing text data effectively. Here's a detailed comparison table to highlight the differences between these two types:

| **Aspect** | **String** | **&str** (String Slice) |
| --------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| **Type** | Owned, growable string | Borrowed reference to a string |
| **Storage** | Heap (dynamically allocated) | Typically inlined or statically allocated; points to some memory region holding string data |
| **Mutability** | Mutable: can be modified, grown, and shrunk | Immutable by default |
| **Creation** | Created with `String::new()`, `String::from("literal")`, or `"literal".to_string()` | Created by directly referencing a string literal: `let s: &str = "literal";` or as a borrow from a `String`: `let s: &str = &some_string;` |
| **Common Use Cases** | Used when you need to modify or own the data | Used for viewing or referencing string data without ownership concerns |
| **Lifetimes** | Managed automatically, scope-based | Must be explicitly considered in function signatures and structs if they outlive their source |
| **Performance** | Slightly slower due to allocations and resizing | Faster access, no allocation needed |
| **Methods Available** | All string methods available plus methods for modification and capacity management | Limited to methods that do not modify the data |
| **Functionality** | Can be passed to functions expecting `&str` with a reference (`&`) | Cannot be directly converted to `String` without creating a new owned instance |
| **Example Creation** | `let mut s = String::from("hello"); s.push('w');` | `let s = "hello";` |
| **Cloning/Copying** | Requires explicit cloning (`s.clone()`) to duplicate because it owns its data | Can be copied with simple assignment, as it is just a reference |
| **Memory Management** | Programmer must manage growth and size, but Rust handles allocation and deallocation | No memory management required by the programmer, as it does not own data |

## Further information

- [Strings](https://doc.rust-lang.org/book/ch08-02-strings.html)
4 changes: 2 additions & 2 deletions exercises/09_strings/strings1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
// Execute `rustlings hint strings1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE
// https://doc.rust-lang.org/book/ch08-02-strings.html

fn main() {
let answer = current_favorite_color();
println!("My current favorite color is {}", answer);
}

fn current_favorite_color() -> String {
"blue"
"blue".to_string() // Convert string slice (type &str) to owned String
}
4 changes: 1 addition & 3 deletions exercises/09_strings/strings2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@
// Execute `rustlings hint strings2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

fn main() {
let word = String::from("green"); // Try not changing this line :)
if is_a_color_word(word) {
if is_a_color_word(word.as_str()) { // Conver owned String to string slice &str to pass to function
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");
Expand Down
18 changes: 12 additions & 6 deletions exercises/09_strings/strings3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,27 @@
// Execute `rustlings hint strings3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE
// https://doc.rust-lang.org/book/ch08-02-strings.html#updating-a-string

fn trim_me(input: &str) -> String {
// TODO: Remove whitespace from both ends of a string!
???
input.trim().to_string()
}

fn compose_me(input: &str) -> String {
// TODO: Add " world!" to the string! There are multiple ways to do this!
???
// Add " world!" to the string!
// String::from(input) + " world!"
// input.to_string() + " world!";
// input.to_string() + &" world!".to_string()
// format!("{} world!", input)
let mut s = String::from(input);
s.push_str(" world!");
s
}

fn replace_me(input: &str) -> String {
// TODO: Replace "cars" in the string with "balloons"!
???
// Replace "cars" in the string with "balloons"!
input.replace("cars", "balloons")
}

#[cfg(test)]
Expand Down
22 changes: 10 additions & 12 deletions exercises/09_strings/strings4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
//
// No hints this time!

// I AM NOT DONE

fn string_slice(arg: &str) {
println!("{}", arg);
}
Expand All @@ -17,14 +15,14 @@ fn string(arg: String) {
}

fn main() {
???("blue");
???("red".to_string());
???(String::from("hi"));
???("rust is fun!".to_owned());
???("nice weather".into());
???(format!("Interpolation {}", "Station"));
???(&String::from("abc")[0..1]);
???(" hello there ".trim());
???("Happy Monday!".to_string().replace("Mon", "Tues"));
???("mY sHiFt KeY iS sTiCkY".to_lowercase());
string_slice("blue");
string("red".to_string());
string(String::from("hi"));
string("rust is fun!".to_owned());
string("nice weather".into());
string(format!("Interpolation {}", "Station"));
string_slice(&String::from("abc")[0..1]);
string_slice(" hello there ".trim());
string("Happy Monday!".to_string().replace("Mon", "Tues"));
string("mY sHiFt KeY iS sTiCkY".to_lowercase());
}

0 comments on commit 151d372

Please sign in to comment.