Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 8.2 Storing UTF-8 Encoded Text with Strings
- // "strings" in Rust means String and &str for Owned and Borrowed form respectively.
- // They both are UTF-8 encoded
- fn main() {
- // Create a new string
- {
- let mut s = String::new(); // create empty string, to load data into it later
- let data = "initial contents";
- let s = data.to_string(); // convert from other type that implement Display trait
- let s = "initial contents".to_string(); // load directly from string literal
- let s = String::from("initial contents"); // use String associate function
- let hello = String::from("สวัสดีครับ");
- println!("{}", hello);
- }
- // Update a string
- {
- let mut s1 = String::from("foo");
- let s2 = "bar";
- s1.push_str(s2); // push_str take a string slice, in this case complier will coerce s2 into &s2[..]
- println!("{}, {}", s1, s2);
- s1.push('!'); // append only one character
- println!("{}", s1);
- }
- // Concatenation with + Operator
- {
- let s1 = String::from("Hello, ");
- let s2 = String::from("World!");
- let s3 = s1 + &s2; // add operator will deref coerce &String into &str -- &s2 into &s2[..]
- // so s2 still available here, as add operator does'nt take ownership
- // but s1 is no longer valid after this, as ownership has moved into s3
- }
- // Concatenation with format! Macro
- {
- let s1 = String::from("tic");
- let s2 = String::from("tac");
- let s3 = String::from("toe");
- let s = format!("{}-{}-{}", s1, s2, s3); // format! works the same way as println!
- // it also never take ownership of any of its parameters
- }
- // Indexing to Strings
- {
- let s1 = String::from("Hello");
- // let h = s1[0]; <- this statement will get error as indexing on Unicode Char might return unexpedted result
- let len1 = String::from("Hello").len(); // this is just 5 bytes
- let len2 = String::from("สวัสดี").len(); // this is 18 bytes
- println!("len1: {}, len2: {}", len1, len2);
- let hello = "สวัสดี";
- let s = &hello[0..3]; // this is valid as long as range is in the char boundary
- // let s = &hello[0..2] <- this slice has invalid range for first char boundary
- println!("{}", s);
- }
- // Interating over Strings
- {
- // fetching each char out of string
- for c in "สวัสดี".chars() {
- println!("{}", c);
- }
- // fetching each raw byte out of string
- for b in "สวัสดี".bytes() {
- println!("{}", b);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement