Strings Overview

In Rust, strings are represented using three main types: str, &str, and String.

str is a primitive type that represents a sequence of Unicode scalar values. It is often used as a slice type to represent borrowed string data. For example, a function that takes a &str argument can accept either a string slice or a string literal.

&str is a string slice type that represents a borrowed view into a sequence of Unicode scalar values. It is a read-only type that cannot be modified. String slices are often used to pass string data between functions or to extract substrings from a larger string. For example:

fn main() {
  let message = "hello, world!";
  let first_word = &message[0..5];
  println!("The first word is {}", first_word);
} 

In this code, message is a string literal that is assigned to a variable. The & symbol is used to create a string slice that represents the first five characters of the message string. This string slice is then printed using the println! macro.

String is a dynamically-sized string type that represents a sequence of Unicode scalar values. It is a mutable type that can be modified by appending, inserting, or removing characters. Strings are often used to represent user input, file data, or other dynamic text content. For example:

fn main() {
  let mut message = String::from("hello");
  message.push_str(", world!");
  println!("{}", message);
} 

In this code, a new String is created using the String::from function, which takes a string literal as an argument. The push_str method is then used to append another string to the end of the message string. The final println! statement prints the modified message string.

It's important to note that String and &str are different types that represent different kinds of string data. String is a dynamically-sized string that is owned by the program, while &str is a borrowed view into a string that is owned by another variable or data structure. Understanding the differences between these types and how to use them correctly is an important part of writing Rust programs that handle string data.

Complete and Continue