Skip to content

Commit 6f2d714

Browse files
authored
[Edit] Rust: Strings (#6609)
1 parent fe67c3e commit 6f2d714

File tree

1 file changed

+166
-45
lines changed

1 file changed

+166
-45
lines changed

content/rust/concepts/strings/strings.md

Lines changed: 166 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,27 @@
22
Title: 'Strings'
33
Description: 'Strings in Rust are encodings of UTF-8 sequences, which can be created, manipulated and referenced.'
44
Subjects:
5-
- 'Computer Science'
65
- 'Code Foundations'
6+
- 'Computer Science'
77
Tags:
88
- 'Data Structures'
9-
- 'Strings'
109
- 'Index'
10+
- 'Strings'
11+
- 'Unicode'
1112
CatalogContent:
1213
- 'learn-rust'
1314
- 'paths/computer-science'
1415
---
1516

16-
**Strings** in Rust diverge a little bit from conventional programming languages. The approach to string manipulation in Rust is influenced by its system-focused design. There are two types of strings that differ in various aspects such as modification, performance of operations and ownership rules.
17+
In Rust, a **string** is essentially a sequence of Unicode characters encoded in UTF-8, which can be created, manipulated and referenced. For example, each character in the "Codecademy Rust Strings" string is a valid Unicode entity, i.e., "C", "o", "d", "e", "c", and so on.
1718

18-
Tackling data structures of variable size, such as strings, can get a bit tricky and Rust has its own spin on it. In Rust, a string is essentially a sequence of Unicode characters encoded in UTF-8. For example, each character in the "Codecademy Rust concept," string is a valid Unicode entity, i.e., "C," "o," "d," "e," "c," and so on.
19+
Rust Strings diverge a little bit from conventional programming languages. The approach to string manipulation in Rust is influenced by its system-focused design. Though tackling them can get a bit tricky, they are essential for tasks such as reading user input, handling file paths, formatting output, managing configuration values, and communicating over networks.
1920

20-
## String types
21+
## Types of Strings in Rust
2122

22-
In Rust, there are two main types related to strings, each serving a specific purpose.
23+
In Rust, there are two types of strings that differ in various aspects such as modification, performance of operations, and [ownership](https://www.codecademy.com/resources/docs/rust/ownership) rules:
2324

24-
1. **`String`**
25+
### 1. `String`
2526

2627
- **Description:** A heap-allocated, growable, and mutable string type.
2728
- **Usage:** Used when dynamic string manipulation and ownership transfer are required.
@@ -30,91 +31,211 @@ In Rust, there are two main types related to strings, each serving a specific pu
3031
let mut dynamic_string = String::from("Hello, Rust!");
3132
```
3233

33-
1. **`&str` (String Slice)**
34+
### 2. `&str` (String Slice)
3435

35-
- **Description:** A reference to a sequence of UTF-8 bytes, often used as a view into a `String` or a string
36-
literal.
36+
- **Description:** A reference to a sequence of UTF-8 bytes, often used as a view into a `String` or a string literal.
3737
- **Usage:** Commonly used for string references without ownership or when dealing with parts of a string.
3838

3939
```rust
4040
let string_literal: &str = "Hello, Rust!";
4141
```
4242

43-
> **Note:** These string types cover various scenarios, from dynamic and mutable strings `String` to static and immutable string slices `&str`. The type of string should be chosen depending on the specific requirements and the characteristics of the data being manipulated.
43+
> **Note:** These string types cover various scenarios, from dynamic and mutable strings (`String`) to static and immutable string slices (`&str`). The string type should be chosen depending on the specific requirements and the characteristics of the data being manipulated.
44+
45+
## Creating Strings in Rust
46+
47+
There are different ways to create a string in Rust:
48+
49+
### 1. Using `String::from()`
50+
51+
This example creates a string using `String::from()` in Rust:
4452

45-
## Creating Strings
53+
```rust
54+
let str = String::from("Hello");
55+
```
4656

47-
Here is an example of creating a string using `String::new()`:
57+
### 2. Using `String::new()`
58+
59+
This example creates a string using `String::new()` in Rust:
4860

4961
```rust
5062
let mut empty_string = String::new();
63+
empty_string.push_str("Hello");
5164
```
5265

53-
## String Manipulation
66+
`String::new()` only allows us to create an empty string. After creating it, a value can be assigned to it using the `.push_str()` method.
5467

55-
### Concatenation
68+
## Concatenating Strings in Rust
5669

57-
In Rust, there are multiple ways to concatenate strings. Here is a list of concatenation operators including examples:
70+
There are several ways to concatenate strings in Rust:
5871

59-
**`+` Operator:**
72+
### `+` Operator
6073

61-
- **Usage:** Concatenating two strings.
74+
- **Usage:** Concatenates two strings.
6275
- **Ownership:** Consumes the left operand.
63-
- **Borrowing:** To concatenate with a borrowed string (sliced out of another string using `&str`), it is necessary to explicitly borrow it using the `&` operator.
76+
- **Borrowing:** To concatenate with a borrowed string (sliced out of another string using `&str`), it is necessary to explicitly borrow it using the `&` [operator](https://www.codecademy.com/resources/docs/rust/operators).
6477

6578
```rust
66-
let hello = String::from("Hello, ");
67-
let world = String::from("World!");
68-
let hello_world = hello + &world; // Ownership of 'hello' is moved, 'world' is borrowed
79+
fn main() {
80+
let hello = String::from("Hello, ");
81+
let world = String::from("World!");
82+
83+
let hello_world = hello + &world; // Ownership of 'hello' is moved, 'world' is borrowed
84+
85+
println!("{}", hello_world);
86+
}
87+
```
88+
89+
Here is the output:
90+
91+
```shell
92+
Hello, World!
6993
```
7094

71-
**`+=` Operator:**
95+
### `+=` Operator
7296

73-
- **Usage:** In-place concatenation operation.
97+
- **Usage:** Concatenates two strings in-place.
7498
- **Ownership:** Consumes the existing string on the left operand and appends to it.
7599
- **Borrowing:** It works directly with the mutable reference of the left operand, but the ownership of the left operand is transferred to the result.
76100

77101
```rust
78-
let mut hello = String::from("Hello, ");
79-
let world = String::from("World!");
80-
hello += &world; // Appends 'World!' to the existing 'Hello, '
102+
fn main() {
103+
let mut hello = String::from("Hello, ");
104+
let world = String::from("World!");
105+
106+
hello += &world; // Appends 'World!' to the existing 'Hello, '
107+
108+
println!("{}", hello);
109+
```
110+
111+
Here is the output:
112+
113+
```shell
114+
Hello, World!
81115
```
82116

83-
**`format!` Macro:**
117+
### `format!` Macro
84118

85119
- **Usage:** Creates a new string by formatting text, allowing string interpolation.
86-
- **Ownership:** It does not involve ownership transfer and is a convenient way to create strings without borrowing
87-
or ownership concerns.
120+
- **Ownership:** It does not involve ownership transfer and is a convenient way to create strings without borrowing or ownership concerns.
88121

89122
```rust
90-
let hello = String::from("Hello, ");
91-
let world = String::from("World!");
92-
let hello_world = format!("{}{}", hello, world); // Creates a new string without ownership issues
123+
fn main() {
124+
let hello = String::from("Hello, ");
125+
let world = String::from("World!");
126+
127+
let hello_world = format!("{}{}", hello, world); // Creates a new string without ownership issues
128+
129+
println!("{}", hello_world);
130+
}
93131
```
94132

95-
> **Note:** When working with strings in Rust, it's crucial to be mindful of ownership and borrowing semantics, especially when using operators like `+`. The operator `+` is used to create a new string while `+=` is used to modify an existing string in place. To concatenate strings with interpolation the `format!` macro provides a flexible and ownership-friendly way.
133+
Here is the output:
96134

97-
### Slicing & Appending with `push_str` and `push`
135+
```shell
136+
Hello, World!
137+
```
138+
139+
> **Note:** When working with strings in Rust, it's crucial to be mindful of ownership and borrowing semantics, especially when using operators like `+`. The operator `+` is used to create a new string while `+=` is used to modify an existing string in-place. To concatenate strings with interpolation, the `format!` macro provides a flexible and ownership-friendly way.
140+
141+
## Slicing and Appending Strings in Rust
142+
143+
In this example, the `.push_str()` method is used to append a string slice to the existing string `message`, whereas the `.push()` method is used to add the character `!` to the end of the concatenated string:
98144

99145
```rust
100-
let mut message = String::from("Rust");
101-
message.push_str(" Programming");
102-
message.push('!');
103-
let part_of_message = &message[0..5];
146+
fn main() {
147+
let mut message = String::from("Rust");
148+
149+
message.push_str(" Programming");
150+
message.push('!');
151+
152+
println!("{}", message);
153+
}
104154
```
105155

106-
In the example above, `push_str` is used to append a string slice to the existing string `message`, and `push` is used to add the character `!` to the end of the concatenated string.
156+
Here is the output:
157+
158+
```shell
159+
Rust Programming!
160+
```
107161

108162
## Referencing Strings
109163

110-
To reference parts of a string without ownership `&str` can be used as follows:
164+
This example demonstrates the usage of `&str` to reference parts of a string without ownership:
111165

112166
```rust
113-
let full_string = String::from("Hello, World!");
114-
let slice = &full_string[0..5];
167+
fn main() {
168+
let full_string = String::from("Hello, World!");
169+
170+
let slice = &full_string[0..5];
171+
172+
println!("{}", slice);
173+
}
174+
```
175+
176+
Here is the output:
177+
178+
```shell
179+
Hello
115180
```
116181

117182
Here, `&full_string[0..5]` creates a reference to the first five characters of `full_string`.
118183

119-
A certain familiarity with the described methods and operators as well as the concept of string slices is crucial to
120-
work efficiently with and fully grasp the syntax of Rust strings.
184+
## Iterating over Strings in Rust
185+
186+
The `.chars()` method can be used to return an iterator of characters in a string, which can then be looped over:
187+
188+
```rust
189+
fn main() {
190+
let str = String::from("Rust");
191+
192+
for char in str.chars() {
193+
println!("{}", char);
194+
}
195+
}
196+
```
197+
198+
Here is the output:
199+
200+
```shell
201+
R
202+
u
203+
s
204+
t
205+
```
206+
207+
## Frequently Asked Questions
208+
209+
### 1. How do I convert between `String` and `&str`?
210+
211+
`String` to `&str`: Use `.as_str()` or dereference (`&s`).
212+
213+
```rust
214+
let s = String::from("Hello");
215+
216+
// Method 1: Using .as_str()
217+
let slice1: &str = s.as_str();
218+
219+
// Method 2: Using dereferencing
220+
let slice2: &str = &s;
221+
```
222+
223+
`&str` to `String`: Use `.to_string()` or `String::from()`.
224+
225+
```rust
226+
let slice = "Hello";
227+
228+
// Method 1: Using .to_string()
229+
let s1 = slice.to_string();
230+
231+
// Method 2: Using String::from()
232+
let s2 = String::from(slice);
233+
```
234+
235+
### 2. Why does Rust have 2 string types?
236+
237+
Rust separates strings into `String` and `&str` to balance performance and flexibility. `&str` is lightweight and fast, perfect for reading or referencing text, while `String` is ideal for ownership and mutation. This separation ensures memory safety and efficient handling of text data.
238+
239+
### 3. What is the difference between Rust string and C string?
240+
241+
Rust strings are safe and UTF-8 encoded, while [C strings](https://www.codecademy.com/resources/docs/c/strings) (`char*`) are null-terminated and unsafe. Rust avoids common C string pitfalls like buffer overflows by enforcing strict memory and type safety, at the cost of some complexity.

0 commit comments

Comments
 (0)