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

Strings

Strings are one of the most frequently used data types in any programming language. In Rust, they are usually found in two forms: the &str type (pronounced stir) and the String type. Rust strings are guaranteed to be valid UTF-8 encoded byte sequences. They are not null terminated as in C strings and can contain null bytes in-between them. The following program shows the two types in action:

// strings.rs

fn main() {
let question = "How are you ?"; // a &str type
let person: String = "Bob".to_string();
let
namaste = String::from("??????"); // unicodes yay!

println!("{}! {} {}", namaste, question, person);
}

In the preceding code, person and namaste are of type String, while question is of type &str. There are multiple ways you can create String types. Strings are allocated on the heap, while &str types are usually pointers to an existing string, which could either be on stack, the heap, or a string in the data segment of the compiled object code. The & is an operator that is used to create a pointer to any type. After initializing the strings in the preceding code, we then use the println! macro to print them together using format strings. That's the very basics of strings. Strings are covered in detail in Chapter 7,  Advanced Concepts.

主站蜘蛛池模板: 黑山县| 永兴县| 上高县| 宕昌县| 修水县| 封开县| 江北区| 武清区| 额济纳旗| 营山县| 石泉县| 敦煌市| 敦煌市| 龙山县| 弋阳县| 大余县| 金坛市| 元江| 平利县| 周宁县| 阿合奇县| 延安市| 兴城市| 滨海县| 朔州市| 贞丰县| 奉化市| 道孚县| 乌兰浩特市| 锡林浩特市| 曲松县| 安丘市| 双柏县| 闵行区| 天峨县| 德令哈市| 石景山区| 武平县| 泽库县| 彭水| 鸡东县|