Rust functions: Difference between revisions

From wikinotes
Line 36: Line 36:
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
// return void
// return void
fn foo() {  
fn foo() {
     println!("hi");  
     println!("hi");
}
}


Line 49: Line 49:
     (123, String::from("abc"))
     (123, String::from("abc"))
}
}
</syntaxhighlight>
Notes that rust supports unpacking multiple variables.
<syntaxhighlight lang="rust">
fn foo() -> (i32, String) {
    (123, String::from("abc"))
}
let (mynum, mystr) = foo();
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Return Values -->
</blockquote><!-- Return Values -->
</blockquote><!-- Function Signatures -->
</blockquote><!-- Function Signatures -->

Revision as of 17:05, 7 February 2023

Expressions vs Statements

  • statements include actions without a return value (ends in ;)
  • expressions include actions with a return value (no ;)

statement

{
    let y = 1;
    y += 1;
} // no return val

expression

let x = {
    let y = 1;
    y += 1       // <-- no semicolon
} // returns 2

Function Signatures

Params

fn main(num: u8) {
    println!("{}", num);
}

Return Values

// return void
fn foo() {
    println!("hi");
}

// single return value
fn foo() -> i32 {
    123 // <-- return value (no semicolon)
}

// multiple return values
fn foo() -> (i32, String) {
    (123, String::from("abc"))
}

Notes that rust supports unpacking multiple variables.

fn foo() -> (i32, String) {
    (123, String::from("abc"))
}

let (mynum, mystr) = foo();