Home Rust Programming String in Rust Programming Language

String in Rust Programming Language

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:

  1. String Object(String)
  2. 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:

  1. to_string(): Converts a given value
  2. push(): Appends the given char to the end of this String.
  3. push_str(): Appends a given string slice onto the end of this String.
  4. pop(): Removes the last character from the string buffer and returns it.
  5. len(): Returns the length of the String in bytes, not chars 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);
  6. remove(): Removes a char from this String at a byte position and returns it.
  7. clear(): Truncate the String, removing all its content. The string will have the size 0, but the capacity of the string will not change.
  8. 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, so parse() returns a Result 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.

str is an immutable sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer, hence it most commonly appears as &str: a reference to some UTF-8 data, normally called a “string slice”

Unlike a String, a &stris 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:

  1. String slices are often used when passing strings as arguments to functions or when slicing a String into smaller sub-strings.
  2. Unlike a String, &str cannot be directly modified, but it can be converted to a String using the to_owned method.
  3. 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.
  4. &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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here