Guest User

Untitled

a guest
Jan 18th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. // Investigate 'return' and ';'
  2. // NOTE: when doing early returns inside a 'if' or 'for' loop, the idiomatic
  3. // versions won't work. We have to use the keyword 'return' explicitly.
  4.  
  5. // idiomatic
  6. fn plus_one(x: i32) -> i32 { // given in the official book
  7. // x + 1; // GM: doesn't work. Error: expected i32, found ().
  8. // Compiler suggests to remove ';'. This makes sense because
  9. // ';' changes the type of x+1 to ().
  10. x + 1 // GM: indeed, it works after removing ';'
  11. }
  12.  
  13. // non-standard style
  14. fn plus_one2(x: i32) -> i32 { // given in the official book
  15. return x + 1; // GM: this works because I guess 'return' explicitly sends
  16. // the value of (x+1), which has a type i32, out of the function.
  17. // The semicolon ';' then makes the type of the entire
  18. // expression (return x + 1) to be (). But it also works
  19. // if we drop ";", see below.
  20. }
  21.  
  22. // non-standard style
  23. fn plus_one3(x: i32) -> i32 { // given in the official book
  24. return x + 1 // GM: notice we're leaving out the semicolon ";" here.
  25. // This also works. So the tentative conclusion is
  26. // when using 'return', it doesn't matter if you also
  27. // add ";" or not at the end.
  28. }
  29.  
  30. /* similarly, let's check with other data types */
  31.  
  32. // idiomatic
  33. fn return_empty_vec() -> Vec<u32> {
  34. vec![]
  35. }
  36.  
  37. // non-idiomatic
  38. fn return_empty_vec2() -> Vec<u32> {
  39. return vec![];
  40. }
  41. fn return_empty_vec3() -> Vec<u32> {
  42. return vec![]
  43. }
  44.  
  45.  
  46. // idiomatic
  47. fn greeting(name: &str) -> String {
  48. format!("Hi there, {}", name)
  49. }
  50.  
  51. // non-idiomatic
  52. fn greeting2(name: &str) -> String {
  53. return format!("Hi there, {}", name);
  54. }
  55. fn greeting3(name: &str) -> String {
  56. return format!("Hi there, {}", name)
  57. }
  58.  
  59.  
  60. fn main() {
  61. println!("{}", plus_one(1));
  62. println!("{}", plus_one2(1));
  63. println!("{}", plus_one3(1));
  64.  
  65. println!("{:?}", return_empty_vec());
  66. println!("{:?}", return_empty_vec2());
  67. println!("{:?}", return_empty_vec3());
  68.  
  69. println!("{}", greeting("gmlang"));
  70. println!("{}", greeting2("gmlang"));
  71. println!("{}", greeting3("gmlang"));
  72. }
Add Comment
Please, Sign In to add comment