Skip to content

Instantly share code, notes, and snippets.

What's this?

I wanted a reference which covered a small piece of rust to help people get over one piece of the learning curve! What was that piece? How to call functions and return stuff. I know it sounds a little absurd to have to write a tutorial on how to call and return, but rust makes it a little more challenging than other languages in order to be as neato-keen as it is.

This tutorial assumes that you've probably already learned another programming language and can guess at the functionality of some of these snippets (or that you've looked at some other, more complete rust tutorials).

Calling functions

Can't touch this

By default, variables are immutable in rust. So the following is an error (run it):

fn main() {

What's this?

This is a follow-up to my silly simple rust tutorial. Basically, there's a lot of weird edgecases with lifetimes, and I wanted to avoid cluttering up the main part of the tutorial.

Lifetime, why are you such a boring network?

Alright, let's get right into it:

YOU GUESSED WRONG! IN PROGRESS

We can show ways that this guess can be wrong! Let's make the first example from this section a little different:

fn electric_slide() -> &'static str {
 let x = String::from("It's electric! ");
fn main() {
let x = 5;
x = 10; // ERROR: x is immutable!
println!("Can't touch this: Hammer Pants x {}", x);
}
fn main() {
let mut x = 5;
x = 10;
println!("Can't touch this: Hammer Pants x {}", x);
}
fn main() {
let x = String::from("Hello");
foo(x);
println!("{} from the other side.", x); // ERROR: we gave away x to foo when we called it!
}
fn foo(bar: String) -> () {
println!("{} world!", bar);
}
fn main() {
let x = String::from("Hello");
foo(x.clone()); // Give away a full copy of x to foo
println!("{} from the other side.", x);
}
fn foo(bar: String) -> () {
println!("{} world!", bar); // I own this bar. I serve good beer.
}
fn main() {
let x = String::from("Hello");
foo(&x); // Give away an immutable reference of x to foo
println!("{} from the other side.", x);
}
fn foo(bar: &String) -> () {
println!("{} world!", bar);
}
fn main() {
let mut x = String::new();
x.push_str("Break on through");
println!("{} to the other side.", x);
}
fn main() {
let mut x = String::new();
foo(&x);
println!("{} to the other side.", x);
}
fn foo(bar: &String) -> () {
bar.push_str("Break on through"); // ERROR: x is immutable!
}
fn main() {
let mut x = String::new();
foo(x);
println!("{} to the other side.", x); // ERROR: we gave away x!
}
fn foo(mut bar: String) -> () {
bar.push_str("Break on through");
}