Welcome to our in-depth guide on String Literals in Rust! Today, we'll dive into the world of text representation in this powerful programming language.
In Rust, string literals are sequences of characters enclosed in double quotes ("). They're used to represent text, which is a crucial part of many programming tasks.
let my_string = "Hello, World!";š” Pro Tip: You can also use single quotes (') for string literals, but they're less common and have limitations, such as not allowing embedded escape sequences (we'll talk about these later).
Rust has two main string types: &str (immutable string slices) and String (growable vectors of UTF-8 bytes). We'll cover both, but today, let's focus on the simpler &str.
Sometimes, we need to include special characters in our strings. To do this, Rust uses escape sequences. The most common ones are:
\n: Newline\t: Tab\\: Backslash\": Double quote\': Single quotelet my_escaped_string = "Hello\nWorld!";To get the length of a string, you can use the len() function:
let my_string = "Hello, World!";
let len = my_string.len();
println!("The length of the string is: {}", len);To access a character at a specific index, you can use square brackets ([]):
let my_string = "Hello, World!";
let first_char = my_string[0];
println!("The first character is: {}", first_char);š” Pro Tip: Remember that Rust uses zero-based indexing. The first character is at index 0.
To concatenate strings, you can use the + operator:
let greeting = "Hello";
let world = " World!";
let combined = greeting.to_string() + " " + world;
println!("{}", combined);š” Pro Tip: If you want to concatenate strings more efficiently, consider using format! macro:
let greeting = "Hello";
let world = " World!";
let combined = format!("{} {}", greeting, world);
println!("{}", combined);What is the correct way to get the length of a string in Rust?
In this lesson, we learned about string literals in Rust, including:
&str and StringIn the next lesson, we'll delve into the String type and explore more string manipulation techniques. Until then, happy coding! š”šÆ