You are currently viewing Rust Strings Tutorial with Code Examples

Rust Strings Tutorial with Code Examples

  • Post author:
  • Post category:Rust
  • Post comments:0 Comments
  • Post last modified:May 11, 2024

Strings are fundamental data types in any programming language, including Rust. In this tutorial, we’ll dive deep into understanding Rust strings, covering basic operations, common pitfalls, and best practices. Whether you’re new to Rust or looking to improve your string-handling skills, this guide has got you covered.

What are Strings in Rust?

In Rust, strings are sequences of Unicode scalar values encoded as UTF-8. The standard library provides the String type, which is a growable, UTF-8 encoded string. Additionally, Rust has string slices (&str), which are immutable views into strings.

Creating Strings

Using String Literals

You can create a String from a string literal using the String::from function:

let hello = String::from("Hello, world!");

Converting from &str

You can also create a String from a string slice (&str) using the to_string method or the into keyword:

let s1 = "Hello".to_string();
let s2: String = "World".into();

Basic String Operations

Concatenation

You can concatenate two strings using the + operator or the format! macro:

let hello = "Hello".to_string();
let world = "World".to_string();

let hello_world = hello + " " + &world;
// or
let hello_world = format!("{} {}", hello, world);

Indexing

You can’t index into a String because it’s a wrapper over a byte buffer, but you can iterate over its characters:

let s = String::from("rust");
for c in s.chars() {
    println!("{}", c);
}

String Slices (&str)

String slices (&str) are references to UTF-8 encoded strings. They are immutable and are often used for string processing without owning the data.

fn string_length(s: &str) -> usize {
    s.len()
}

let s = "Hello, world!";
println!("Length: {}", string_length(s));

Conclusion

Strings in Rust are versatile and powerful. Understanding how to work with them efficiently is crucial for writing reliable and idiomatic Rust code. With the knowledge gained from this tutorial, you’re well-equipped to handle strings effectively in your Rust projects.

Leave a Reply