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

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:

主站蜘蛛池模板: 晋州市| 滁州市| 威海市| 永寿县| 崇义县| 东乡| 遵义市| 万州区| 旅游| 宁南县| 漠河县| 德令哈市| 德令哈市| 枣阳市| 醴陵市| 海城市| 松溪县| 出国| 新丰县| 平谷区| 康乐县| 芒康县| 北宁市| 来宾市| 敖汉旗| 温州市| 疏勒县| 南和县| 乌兰浩特市| 固原市| 临汾市| 黔南| 蓝田县| 福泉市| 白朗县| 青冈县| 高尔夫| 黄梅县| 山丹县| 中西区| 丰镇市|