Open In App

Rust – ToString and FromStr Trait

Last Updated : 21 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Rust is a multi-paradigm programming language like C++ syntax that was designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. In this article, we will see the concept of ToString and FromStr Trait. 

ToString Trait:

We can convert any type to a string type. ToString trait is used for converting a type to a String in Rust. By implementation of the fmt::Display trait, the ToString trait gets automatically implemented.

Example 1:

Rust




// Rust program for ToString and FromStr Trait
use std::fmt;
  
struct GFG {
    value: i32
}
  
impl fmt::Display for GFG {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Value of item is : {}", self.value)
    }
}
  
fn main() {
    let gfg = GFG { value: 20 };
    println!("{}", gfg.to_string());
}


Output:

 

String Parsing Using FromStr Trait:

In certain situations, we need to convert strings to numbers. FromStr trait is implemented in these scenarios. We just need to implement the functionality by implementing the FromStr trait for the required type

Example 2:

Rust




// Rust program for String Parsing using FromStr trait
fn main() {
    let variable_one: i32 = "1".parse().unwrap();
    let variable_two = "2".parse::<i32>().unwrap();
    let variable_three = "3".parse::<i32>().unwrap();
  
    let sum = variable_one + variable_two + variable_three;
    println!("Sum of the variables are: {:?}", sum);
}


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads