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

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 189字
  • 2021-07-02 23:07:16

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.

主站蜘蛛池模板: 平遥县| 通山县| 龙陵县| 临朐县| 辽阳县| 尚义县| 隆尧县| 和平县| 柳河县| 涞源县| 玉龙| 临潭县| 慈溪市| 洛浦县| 辽源市| 江永县| 安平县| 抚顺县| 大荔县| 九龙坡区| 高唐县| 黔西| 新绛县| 额敏县| 桂东县| 濮阳县| 周宁县| 武陟县| 吕梁市| 东源县| 辽阳市| 长沙市| 金寨县| 庄浪县| 炎陵县| 奉化市| 金堂县| 太仓市| 绥芬河市| 扶绥县| 南昌市|