To and From Strings

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn about converting to and from strings in Rust. To convert any type to a string, we can implement the ToString trait for the type. Alternatively, we can implement the fmt::Display trait, which automatically provides the ToString trait and allows us to print the type using println!. On the other hand, to parse a string into a specific type, such as a number, we can use the parse function along with type inference or by specifying the type using the 'turbofish' syntax. This relies on the FromStr trait, which is implemented for many types in the standard library. If we want to parse a string into a user-defined type, we can implement the FromStr trait for that type.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/DataStructuresandEnumsGroup(["`Data Structures and Enums`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") rust/AdvancedTopicsGroup -.-> rust/traits("`Traits`") subgraph Lab Skills rust/variable_declarations -.-> lab-99301{{"`To and From Strings`"}} rust/integer_types -.-> lab-99301{{"`To and From Strings`"}} rust/string_type -.-> lab-99301{{"`To and From Strings`"}} rust/function_syntax -.-> lab-99301{{"`To and From Strings`"}} rust/expressions_statements -.-> lab-99301{{"`To and From Strings`"}} rust/method_syntax -.-> lab-99301{{"`To and From Strings`"}} rust/traits -.-> lab-99301{{"`To and From Strings`"}} end

To and from Strings

Converting to String

To convert any type to a String is as simple as implementing the [ToString] trait for the type. Rather than doing so directly, you should implement the fmt::Display trait which automagically provides [ToString] and also allows printing the type as discussed in the section on print!.

use std::fmt;

struct Circle {
    radius: i32
}

impl fmt::Display for Circle {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Circle of radius {}", self.radius)
    }
}

fn main() {
    let circle = Circle { radius: 6 };
    println!("{}", circle.to_string());
}

Parsing a String

One of the more common types to convert a string into a number. The idiomatic approach to this is to use the [parse] function and either to arrange for type inference or to specify the type to parse using the 'turbofish' syntax. Both alternatives are shown in the following example.

This will convert the string into the type specified as long as the [FromStr] trait is implemented for that type. This is implemented for numerous types within the standard library. To obtain this functionality on a user defined type simply implement the [FromStr] trait for that type.

fn main() {
    let parsed: i32 = "5".parse().unwrap();
    let turbo_parsed = "10".parse::<i32>().unwrap();

    let sum = parsed + turbo_parsed;
    println!("Sum: {:?}", sum);
}

Summary

Congratulations! You have completed the To and From Strings lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like