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

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

主站蜘蛛池模板: 彭阳县| 乾安县| 江阴市| 安丘市| 娄底市| 林口县| 尚义县| 腾冲县| 黎川县| 滁州市| 格尔木市| 紫金县| 景东| 镇原县| 乌拉特中旗| 色达县| 腾冲县| 韩城市| 城步| 西贡区| 安化县| 黄龙县| 蓝田县| 黔西| 吉木萨尔县| 平定县| 乐亭县| 崇明县| 铁岭县| 朝阳市| 镇宁| 宜宾县| 西安市| 新乡市| 黎川县| 双江| 伊宁县| 湘潭市| 陈巴尔虎旗| 同仁县| 绥江县|