Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Investigate 'return' and ';'
- // NOTE: when doing early returns inside a 'if' or 'for' loop, the idiomatic
- // versions won't work. We have to use the keyword 'return' explicitly.
- // idiomatic
- fn plus_one(x: i32) -> i32 { // given in the official book
- // x + 1; // GM: doesn't work. Error: expected i32, found ().
- // Compiler suggests to remove ';'. This makes sense because
- // ';' changes the type of x+1 to ().
- x + 1 // GM: indeed, it works after removing ';'
- }
- // non-standard style
- fn plus_one2(x: i32) -> i32 { // given in the official book
- return x + 1; // GM: this works because I guess 'return' explicitly sends
- // the value of (x+1), which has a type i32, out of the function.
- // The semicolon ';' then makes the type of the entire
- // expression (return x + 1) to be (). But it also works
- // if we drop ";", see below.
- }
- // non-standard style
- fn plus_one3(x: i32) -> i32 { // given in the official book
- return x + 1 // GM: notice we're leaving out the semicolon ";" here.
- // This also works. So the tentative conclusion is
- // when using 'return', it doesn't matter if you also
- // add ";" or not at the end.
- }
- /* similarly, let's check with other data types */
- // idiomatic
- fn return_empty_vec() -> Vec<u32> {
- vec![]
- }
- // non-idiomatic
- fn return_empty_vec2() -> Vec<u32> {
- return vec![];
- }
- fn return_empty_vec3() -> Vec<u32> {
- return vec![]
- }
- // idiomatic
- fn greeting(name: &str) -> String {
- format!("Hi there, {}", name)
- }
- // non-idiomatic
- fn greeting2(name: &str) -> String {
- return format!("Hi there, {}", name);
- }
- fn greeting3(name: &str) -> String {
- return format!("Hi there, {}", name)
- }
- fn main() {
- println!("{}", plus_one(1));
- println!("{}", plus_one2(1));
- println!("{}", plus_one3(1));
- println!("{:?}", return_empty_vec());
- println!("{:?}", return_empty_vec2());
- println!("{:?}", return_empty_vec3());
- println!("{}", greeting("gmlang"));
- println!("{}", greeting2("gmlang"));
- println!("{}", greeting3("gmlang"));
- }
Add Comment
Please, Sign In to add comment