Open In App

Rust – Strings

Improve
Improve
Like Article
Like
Save
Share
Report

String data type is a very important part of any programming language. Rust handles strings a bit differently from other languages.  

The String data type in Rust is of two types:

  • String Literal (&str)
  • String Object (String)

String Literal

String Literal or &str are called ‘string slices’, which always point to a legitimate UTF-8 sequence. It is used when we know the value of a string at compile time. They are a set of characters and static by default.

Example 1: Declaring string literals.

Rust




fn main() {
   let website:&str="geeksforgeeks.org";
   let language:&str = "RUST";
   println!("Website is {}",website);
   println!("Language is {}",language);
}


Output:

Website is geeksforgeeks.org
Language is RUST

String Object

The String Object is provided by the Standard Library in Rust. It is not a part of the core language and String is heap-allocated, growable, and not null-terminated. They are commonly created by converting them from a string slice by using the to_string() method.

Example 2: Declaring String Object and converting String Literal to String Object

Rust




fn main() {
   
  // Declaring String Object using from() method 
  let str1 = String::from("Rust Articles"); 
  println!("{}",str1);
   
  // Converting String Literal to String Object
  let str2 = "GeeksforGeeks".to_string();
  println!("{}",str2);
}


Output:

Rust Articles
GeeksforGeeks

Example 3: Create an empty string and then set its value.

Rust




fn main() {
   let mut str1 = String::new();
   str1.push_str("GeeksForGeeks");
   println!("{}",str1);
}


Output:

GeeksForGeeks

Rust allows many methods to be used with Strings just as JAVA does. Also, it supports many methods such as indexing, concatenation, and slicing.



Last Updated : 27 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads