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

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:

主站蜘蛛池模板: 包头市| 芦溪县| 修文县| 麦盖提县| 罗甸县| 平顶山市| 大名县| 榆中县| 余江县| 孟连| 潮州市| 伊金霍洛旗| 富蕴县| 诸城市| 施甸县| 和龙市| 德保县| 孝义市| 繁昌县| 江津市| 水城县| 海南省| 习水县| 新宁县| 定边县| 山东| 苍梧县| 咸宁市| 博白县| 许昌市| 长垣县| 苍溪县| 枣阳市| 栾川县| 宁津县| 庆云县| 四平市| 沧源| 通渭县| 绿春县| 德兴市|