官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 望江县| 金山区| 岚皋县| 望城县| 江达县| 县级市| 辉县市| 武安市| 清河县| 海南省| 宜兰县| 滨州市| 凤凰县| 延寿县| 金沙县| 高雄市| 略阳县| 太保市| 秀山| 山西省| 德安县| 喀什市| 伊通| 福鼎市| 武胜县| 瑞金市| 沁源县| 沾益县| 上高县| 密云县| 石首市| 南投市| 定边县| 永嘉县| 奉新县| 旺苍县| 达州市| 土默特右旗| 阿尔山市| 海丰县| 扎鲁特旗|