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

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

主站蜘蛛池模板: 灵丘县| 平南县| 崇义县| 吉安县| 盘山县| 宁阳县| 石门县| 延庆县| 宜州市| 芜湖县| 沁水县| 肇庆市| 黄冈市| 华池县| 徐水县| 赤水市| 阿尔山市| 永川市| 长海县| 项城市| 岳池县| 积石山| 哈密市| 宁城县| 濮阳市| 昌吉市| 古交市| 饶阳县| 肃宁县| 法库县| 南和县| 怀仁县| 广西| 遂昌县| 乌兰浩特市| 和平县| 内黄县| 综艺| 莫力| 华容县| 凤阳县|