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

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 137字
  • 2021-07-02 23:07:17

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:

主站蜘蛛池模板: 沂南县| 星子县| 温州市| 红河县| 张家港市| 靖江市| 手游| 宝兴县| 舒城县| 健康| 新蔡县| 延寿县| 德庆县| 安泽县| 瑞金市| 江口县| 青冈县| 鸡西市| 西昌市| 清新县| 从化市| 神农架林区| 固镇县| 临泽县| 洛扎县| 汉寿县| 双鸭山市| 金坛市| 稻城县| 天峻县| 鲁山县| 简阳市| 房产| 清苑县| 香河县| 柳河县| 永定县| 安宁市| 伽师县| 兰州市| 天等县|