Rust functions: Difference between revisions

From wikinotes
Line 90: Line 90:
</blockquote><!-- Generics -->
</blockquote><!-- Generics -->
</blockquote><!-- Function Signatures -->
</blockquote><!-- Function Signatures -->
= Closures =
<blockquote>
<syntaxhighlight lang="rust">
// closure w/o params
let say_hi = || println!("hi");
say_hi();
// closure w/ params
let say_hi_to = |name| println!("hi {}", name)
let say_hi_to = |name: &str| println!("hi {}", name)
say_hi_to("alex");
</syntaxhighlight>
</blockquote><!-- Closures -->

Revision as of 16:45, 9 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();

References

References let you pass an argument to a function without transferring ownership.
By default, references are not mutable, but the mut keyword makes it so.

// pass reference to string
fn len(s: &String) -> usize {
    s.len()
}

// if mutable, '&' placed before the keyword
fn len(s: &mut str) -> usize {
    s.len()
}

Generics

fn do_thing<T>(val: T) { ... }

See more details in rust generics.

Closures

// closure w/o params
let say_hi = || println!("hi");
say_hi();

// closure w/ params
let say_hi_to = |name| println!("hi {}", name)
let say_hi_to = |name: &str| println!("hi {}", name)
say_hi_to("alex");