The string is the most important concept in the rust programming language. In Rust programming language the strings are handled a bit differently compared to other languages. String data type in rust can be classified into two categories:
- String Object(String)
- String Literal (&str)
String in Rust
The String
type is the most common string type in rust and it has ownership over the content of the string. It is heap-allocated, growable, and not null-terminated. A String
is stored as a vector of bytes(Vec<u8>
), and guaranteed to be a valid UTF-8 sequence. If you want to deal with non-UTF-8 strings, use OsString
.
To create a new String
in rust, we can use String::new()
:
let mut new_string = String::new();
To create a String
from string literal, we can use String::from()
let new_string = String::from("Hello, Rust!");
We can also create a String
from a vector of UTF-8 bytes using from_utf8
method, as explained below:
#![allow(unused)]
fn main() {
let intmain_text = vec![073,110,116,077,097,105,110,032,240,159,146,187];
// We know these bytes are valid, so we'll use `unwrap()`
let intmain_text = String::from_utf8(intmain_text).unwrap();
assert_eq!("IntMain 💻", intmain_text);
}
String
type supports many other methods. Some of the popular methods are:
- to_string(): Converts a given value
- push(): Appends the given
char
to the end of thisString
. - push_str(): Appends a given string slice onto the end of this
String
. - pop(): Removes the last character from the string buffer and returns it.
- len(): Returns the length of the
String
in bytes, notchar
s or graphemes. It might not be the length of the string.let a = String::from("foo"); assert_eq!(a.len(), 3); let fancy_f = String::from("ƒoo"); assert_eq!(fancy_f.len(), 4); assert_eq!(fancy_f.chars().count(), 3);
- remove(): Removes a
char
from thisString
at a byte position and returns it. - clear(): Truncate the
String
, removing all its content. The string will have the size 0, but the capacity of the string will not change. - parse(): Parses a string slice into another type that implements the
FromStr
trait.It might not always be possible to parse a string slice into the other type, soparse()
returns aResult
indicating possible failure.
&str in Rust
String literals or &str
also called “string slices” is the most primitive string type. A Rust &str
is like a char*
(but a little more sophisticated); it points us to the beginning of a chunk in the same way you can get a pointer to the contents of std::string
.
Unlike a String, a &str
is not owned, meaning it does not have ownership over the data it points to. This allows it to be used with borrowed references and in constant time.
fn main(){ let programming_language = "rust"; let website = "intmain.co"; println!("You are learning {} at {}", programming_language, website); }
A &str
is made up of two components: a pointer to some bytes and a length. &str
is a fixed-length type, meaning its length cannot be changed once it is created.
Here are some key points about &str in Rust:
- String slices are often used when passing strings as arguments to functions or when slicing a String into smaller sub-strings.
- Unlike a String,
&str
cannot be directly modified, but it can be converted to a String using theto_owned
method. - String slices are very efficient due to their lack of ownership and the use of a shared reference, making them ideal for use in situations where memory is limited.
&str
is always a valid UTF-8.
To convent &str
to string to_string() method is available in rust.
Conclusion
String
and &str
are two data types in Rust that are used to represent strings. While they are both used to work with text data, they have different properties and are used in different scenarios. String
is an owned, growable string type. It is a heap-allocated data structure that can be modified, concatenated, and resized. On the other hand, &str
is a string slice, which is a reference to a portion of a string. Unlike String
, &str
does not have ownership over the data it refers to.
In general, String
is used when you need a string that you can modify and concatenate, while &str
is used when you need a string that you cannot modify and will not change, such as for string literals or constant strings.