- 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:

推薦閱讀
- C++面向對象程序設計(微課版)
- PLC編程及應用實戰
- Web程序設計(第二版)
- 利用Python進行數據分析(原書第3版)
- Learning Python Design Patterns
- OpenStack Orchestration
- Nginx Lua開發實戰
- 基于Struts、Hibernate、Spring架構的Web應用開發
- Java Web開發詳解
- Service Mesh實戰:基于Linkerd和Kubernetes的微服務實踐
- 從零開始學算法:基于Python
- MongoDB Cookbook
- Java EE實用教程
- 一覽眾山小:ASP.NET Web開發修行實錄
- Java編程指南:語法基礎、面向對象、函數式編程與項目實戰