Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. // 8.2 Storing UTF-8 Encoded Text with Strings
  2.  
  3. // "strings" in Rust means String and &str for Owned and Borrowed form respectively.
  4. // They both are UTF-8 encoded
  5.  
  6. fn main() {
  7. // Create a new string
  8. {
  9. let mut s = String::new(); // create empty string, to load data into it later
  10.  
  11. let data = "initial contents";
  12. let s = data.to_string(); // convert from other type that implement Display trait
  13.  
  14. let s = "initial contents".to_string(); // load directly from string literal
  15.  
  16. let s = String::from("initial contents"); // use String associate function
  17.  
  18. let hello = String::from("สวัสดีครับ");
  19. println!("{}", hello);
  20. }
  21.  
  22. // Update a string
  23. {
  24. let mut s1 = String::from("foo");
  25. let s2 = "bar";
  26. s1.push_str(s2); // push_str take a string slice, in this case complier will coerce s2 into &s2[..]
  27. println!("{}, {}", s1, s2);
  28.  
  29. s1.push('!'); // append only one character
  30. println!("{}", s1);
  31. }
  32.  
  33. // Concatenation with + Operator
  34. {
  35. let s1 = String::from("Hello, ");
  36. let s2 = String::from("World!");
  37. let s3 = s1 + &s2; // add operator will deref coerce &String into &str -- &s2 into &s2[..]
  38. // so s2 still available here, as add operator does'nt take ownership
  39. // but s1 is no longer valid after this, as ownership has moved into s3
  40. }
  41.  
  42. // Concatenation with format! Macro
  43. {
  44. let s1 = String::from("tic");
  45. let s2 = String::from("tac");
  46. let s3 = String::from("toe");
  47. let s = format!("{}-{}-{}", s1, s2, s3); // format! works the same way as println!
  48. // it also never take ownership of any of its parameters
  49. }
  50.  
  51. // Indexing to Strings
  52. {
  53. let s1 = String::from("Hello");
  54. // let h = s1[0]; <- this statement will get error as indexing on Unicode Char might return unexpedted result
  55.  
  56. let len1 = String::from("Hello").len(); // this is just 5 bytes
  57. let len2 = String::from("สวัสดี").len(); // this is 18 bytes
  58. println!("len1: {}, len2: {}", len1, len2);
  59.  
  60. let hello = "สวัสดี";
  61. let s = &hello[0..3]; // this is valid as long as range is in the char boundary
  62. // let s = &hello[0..2] <- this slice has invalid range for first char boundary
  63. println!("{}", s);
  64. }
  65.  
  66. // Interating over Strings
  67. {
  68. // fetching each char out of string
  69. for c in "สวัสดี".chars() {
  70. println!("{}", c);
  71. }
  72.  
  73. // fetching each raw byte out of string
  74. for b in "สวัสดี".bytes() {
  75. println!("{}", b);
  76. }
  77. }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement