- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 249字
- 2021-07-02 23:07:16
String slices
String slices can be confusing at first sight. We define a string slice like this:
let homeTeam = "Liverpool";
Coming from more dynamic languages, you might think that we are assigning the string Liverpool to the variable binding homeTeam. That's not exactly what happens, however. The homeTeam binding is actually a string slice: a reference to a part of the string that actually resides somewhere else.
The string slice is also not mutable.
The following will not work in Rust:
let homeTeam = "Liverpool"; let result = " beat "; let awayTeam = "Manchester United"; let theString = homeTeam + result + awayTeam;
The compiler will not allow this, and will give an error as follows:

We cannot concatenate the slice directly, since string slices cannot be mutable. To do that, we need to first convert the string slice into something that is mutable, or build the string with something like the format! macro. Let's try them both.
Like before, the to_owned() method takes the slice the method is attached to, and converts it to a String type:
fn main() { let homeTeam = "Liverpool"; let result = " beat "; let awayTeam = "Manchester United"; let fullLine = homeTeam.to_owned() + result + awayTeam; println!("{}", fullLine); }
The to_owned() method is only applied to the first slice. This converts the string slice homeTeam into a String, and using the + operator on a String is fine.
When this is built and executed, you will see the following:

- Clojure Programming Cookbook
- Getting Started with Gulp(Second Edition)
- 高效微控制器C語言編程
- Mastering Ember.js
- Python程序設計(第3版)
- Practical DevOps
- Learning Firefox OS Application Development
- Python面向對象編程:構建游戲和GUI
- Python機器學習基礎教程
- RISC-V體系結構編程與實踐(第2版)
- Android系統(tǒng)原理及開發(fā)要點詳解
- 執(zhí)劍而舞:用代碼創(chuàng)作藝術
- Advanced Express Web Application Development
- “笨辦法”學C語言
- ExtJS Web應用程序開發(fā)指南第2版