Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 6, 2024 13:12
Show Gist options
  • Save max-itzpapalotl/c069707bcdd5d8e7f24733c7199323d7 to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/c069707bcdd5d8e7f24733c7199323d7 to your computer and use it in GitHub Desktop.
2. Functions and Arguments

2. Functions in Rust

Content:

  • Function, no args, calling it.
  • One string argument, default move, not usable any more after move.
  • Immutable ref, can have multiple.
  • Mutable ref, can only have one.
  • Return values, default move.
  • Cannot return reference -> life time tracking.

Our first function

fn f() {
    println!("Hello from f");
}

fn main() {
    println!("Hello world!");
    f();
}

A String argument

fn f(s: String) {
    println!("Hello from f {}", s);
}

fn main() {
    println!("Hello world!");
    let st : String = "abc".to_string();
    f(st);
}

An immutable reference argument

fn f(s: &String) {
    println!("Hello from f {}", s);
}

fn main() {
    println!("Hello world!");
    let st : String = "abc".to_string();
    f(&st);
    println!("Value: {}", st);
}

A mutable reference argument

fn f(s: &mut String) {
    println!("Hello from f {}", s);
    s.push_str("xyz");
}

fn main() {
    println!("Hello world!");
    let mut st : String = "abc".to_string();
    f(&mut st);
    println!("Value: {}", st);
}

Rules of borrowing

fn f(s: &mut String) {
    println!("Hello from f {}", s);
    s.push_str("xyz");
}

fn main() {
    println!("Hello world!");
    let mut st : String = "abc".to_string();
    f(&mut st);
    let a : &String = &st;
    let b : &String = &st;
    println!("Value: {} {} {}", st, a, b);
}
fn f(s: &mut String) {
    println!("Hello from f {}", s);
    s.push_str("xyz");
}

fn main() {
    println!("Hello world!");
    let mut st : String = "abc".to_string();
    f(&mut st);
    let a : &String = &st;
    println!("Value: {}", a);
    let b : &mut String = &mut st;
    println!("Value: {}", b);
}

Return values

fn f(s: &mut String) -> String {
    println!("Hello from f {}", s);
    s.push_str("xyz");
    s.clone() + "abc"
}

fn main() {
    println!("Hello world!");
    let mut st : String = "abc".to_string();
    let t = f(&mut st);
    println!("Value: {} {}", st, t);
}

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment