Building a string

We've seen that we can create a String from a string slice (using to_owned() or the format! macro), or we can create it using String::new().

There are two further ways to help build the string: push adds a single character to the string, and push_str adds an str to the string.

The following shows this in action:

fn main() { 
    let home_team = "Liverpool"; 
    let result = " beat "; 
    let away_team = "Manchester United"; 
    let home_score = '3'; // single character 
    let away_score = "-0"; 
     
 
    let mut full_line = format!("{}{}{} ", home_team, result, away_team); 
         
    // add the character to the end of the String     
    full_line.push(home_score); 
      
    // add the away score to the end of the String 
    full_line.push_str(away_score); 
         
    println!("{}", full_line); 
} 

When this last code snippet is compiled and executed, you will see this:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset