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

Back to Strings

As we saw before perting onto the heap and stack, we can also define a string like this:

let mut myString = String::new(); 

The String:: tells the compiler that we are going to use the standard library, String, and we tell the program that we are going to create a mutable String and store a reference to it on the stack in something called myString.

The dynamic string can be created as either being empty, or with memory preallocated to it. For example, say we want to store the words You'll never walk alone (a total of 23 bytes), preallocating the space for them. This is how to do it:

let mut ynwa = String::with_capacity(23); 
ynwa.push_str("You'll never walk alone"); 

This is just a performance optimization and is not typically required, since Strings grow automatically when they need to. The following does roughly the same job:

let mut ynwa = "You'll never walk alone".to_owned(); 

Rust strings are not null-terminated, and consist entirely of valid Unicode. Therefore, they can contain null bytes and characters from any language, but they may require more bytes than they contain characters.

主站蜘蛛池模板: 铜山县| 穆棱市| 济宁市| 固始县| 岫岩| 台安县| 阆中市| 宣武区| 阳泉市| 达拉特旗| 新昌县| 曲阜市| 英山县| 安丘市| 永定县| 雷州市| 乐业县| 长宁县| 盐边县| 武汉市| 绍兴市| 甘南县| 杭锦后旗| 安平县| 石景山区| 杭锦后旗| 井陉县| 佛坪县| 宁波市| 容城县| 永仁县| 庆云县| 五常市| 左贡县| 巢湖市| 曲阳县| 西畴县| 东莞市| 奉贤区| 德昌县| 岢岚县|