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

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.

主站蜘蛛池模板: 拜泉县| 嘉荫县| 张北县| 玛多县| 长海县| 吉安市| 上饶市| 东山县| 新沂市| 东乌珠穆沁旗| 翁牛特旗| 那曲县| 武隆县| 宝丰县| 兰坪| 开阳县| 章丘市| 新疆| 新安县| 伊春市| 曲松县| 讷河市| 临沭县| 银川市| 海门市| 元氏县| 成武县| 清原| 英山县| 阿拉善左旗| 芦山县| 镇沅| 特克斯县| 开化县| 缙云县| 宜城市| 斗六市| 淳安县| 崇明县| 娱乐| 仁寿县|