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

- Web應(yīng)用系統(tǒng)開發(fā)實(shí)踐(C#)
- Mastering OpenCV Android Application Programming
- Cassandra Design Patterns(Second Edition)
- OpenShift在企業(yè)中的實(shí)踐:PaaS DevOps微服務(wù)(第2版)
- C#程序設(shè)計基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- Node學(xué)習(xí)指南(第2版)
- Webpack實(shí)戰(zhàn):入門、進(jìn)階與調(diào)優(yōu)(第2版)
- QGIS 2 Cookbook
- Application Development with Parse using iOS SDK
- 軟件工程與UML案例解析(第三版)
- Java程序設(shè)計及應(yīng)用開發(fā)
- 城市信息模型平臺頂層設(shè)計與實(shí)踐
- PHP程序設(shè)計高級教程
- Clojure High Performance Programming
- CorelDRAW X6中文版應(yīng)用教程(第二版)