MOCKSTACKS
EN
Questions And Answers

More Tutorials








RUST String Object


The String data type in RUST can be defined in 2 ways:
  • String Literal (&str)
  • String Object (String)

String Literal

String literals (&str) are a predefined hardcoded set of characters for example: let firstName = "Jhon";. String literals are part of module std::str and they are also known as string slices. String literals are static by default which means that they are guaranteed to be valid for the duration of the entire program.

Example of String literals:


fn main() {
 let firstName:&str="John";
 let lastName:&str = "Smith";
 println!("First name is : {} last name :{}",firstName,lastName);
}


String Object

The String object type is provided in Standard Library. Unlike string literal, the string object type is not a part of the core language. It is defined as public structure in standard library pub struct String. String is a growable collection. It is mutable and UTF-8 encoded type. The String object type can be used to represent string values that are provided at
runtime. String object is allocated in the heap.

To create a new String object we will need to use: String::new()

To create a new String object from another String we will need to use: String::from()

Example of String Objects:


fn main(){
 let new_Empty_String = String::new();
 let new_String_From = String::from("Jhon");

 println!("My String is {}",new_Empty_String);
 println!("new String From  is {}",new_String_From );
}

Output for above code:


My String is

new String From is Jhon






Conclusion

In this page (written and validated by ) you learned about Rust String Object . What's Next? If you are interested in completing Rust tutorial, your next topic will be learning about: Rust String Methods - String Object.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.