Strings
String Types in Rust
Section titled “String Types in Rust”Rust has two string types:
String
Section titled “String”- Growable, heap-allocated
- UTF-8 encoded
- Owned type
- Fixed-size string slice
- UTF-8 encoded
- Reference type
Creating Strings
Section titled “Creating Strings”// String
let s1 = String::from("hello");
let s2 = "hello".to_string();
// &str
let s3 = "hello";
String Operations
Section titled “String Operations”Concatenation
Section titled “Concatenation”let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // s1 has been moved and can no longer be used
Appending
Section titled “Appending”let mut s = String::from("hello");
s.push_str(", world!");
s.push('!');
String Slices
Section titled “String Slices”let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
UTF-8 Encoding
Section titled “UTF-8 Encoding”let s = String::from("नमस्ते");
for c in s.chars() {
println!("{}", c);
}
Comparing to JavaScript
Section titled “Comparing to JavaScript”JavaScript has a single string type:
let s1 = "hello";
let s2 = new String("hello");
String Methods
Section titled “String Methods”Length
Section titled “Length”let s = String::from("hello");
let len = s.len(); // 5
Contains
Section titled “Contains”let s = String::from("hello world");
let contains = s.contains("world"); // true
Replace
Section titled “Replace”let s = String::from("hello world");
let s2 = s.replace("world", "rust");
String Formatting
Section titled “String Formatting”let name = "Alice";
let age = 30;
let s = format!("{} is {} years old", name, age);
Conclusion
Section titled “Conclusion”Rust’s string system provides safety and performance through its two string types.