Rust functions: Difference between revisions
From wikinotes
Line 22: | Line 22: | ||
= Function Signatures = | = Function Signatures = | ||
<blockquote> | |||
== Params == | |||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="rust"> | <syntaxhighlight lang="rust"> | ||
fn main() { | fn main(num: u8) { | ||
println!(" | println!("{}", num); | ||
} | } | ||
</syntaxhighlight> | |||
</blockquote><!-- Params --> | |||
== Return Values == | |||
<blockquote> | |||
<syntaxhighlight lang="rust"> | |||
// return void | |||
fn foo() { println!("hi"); } | |||
fn | // single return value | ||
123 | fn foo() -> i32 { | ||
123 // <-- return value (no semicolon) | |||
} | } | ||
fn | // multiple return values | ||
fn foo() -> (i32, String) { | |||
(123, String::from("abc")) | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Return Values --> | |||
</blockquote><!-- Function Signatures --> | </blockquote><!-- Function Signatures --> |
Revision as of 17:03, 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 valexpression
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")) }