Skip to content

Instantly share code, notes, and snippets.

fn main() {
let x = String::from("What is love?");
let y = String::from("Baby don't hurt me,");
let ref_y = print_first_return_second(&x, &y);
print!("{}", y);
take_ownership(y); // ERROR: ref_y is borrowing y! We can't delete y!
print!("{}", ref_y);
}
fn print_first_return_second<'a, 'b>(print_me: &'a str, return_me: &'b str) -> &'b str {
fn main() {
let x = String::from("What is love?");
let y = String::from("Baby don't hurt me,");
let ref_y = print_first_return_second(&x, &y);
print!("{}", y);
print!("{}", ref_y);
take_ownership(x); // This is okay, no one is borrowing x
}
fn print_first_return_second<'a, 'b>(print_me: &'a str, return_me: &'b str) -> &'b str {
fn main() {
let x = String::from("What is love?");
let y = String::from("Baby don't hurt me,");
let ref_y = print_first_return_second(&x, &y);
print!("{}", y);
print!("{}", ref_y);
println!(" no more!");
}
fn print_first_return_second<'a, 'b>(print_me: &'a str, return_me: &'b str) -> &'b str {
fn main() {
let x = String::from("What is love?");
let y = String::from("Baby don't hurt me,");
let ref_y = print_first_return_second(&x, &y);
print!("{}", y);
print!("{}", ref_y);
println!(" no more.");
}
// ERROR: I can't figure out if the returned value is a reference to "print_me" or "return_me"!
fn main() {
let x = String::from("Mysterious first letter!");
let ref_x = first_letter(&x);
take_ownership(x); // ERROR: ref_x still exists and is "borrowing" x
// We can't delete x safely!
println!("{}ystery solved!", ref_x);
}
fn first_letter(input: &str) -> &str {
&input[0..1]
fn main() {
let x = String::from("Mysterious first letter!");
let ref_x = first_letter(&x);
println!("{}ystery solved!", ref_x);
}
// We'll take a reference to a str, and we're returning a reference to a str
fn first_letter(input: &str) -> &str {
&input[0..1] // We're taking a slice, with just the first letter
}
fn main() {
let x = String::new();
let y = foo(x); // Give away x, and put the result into y
println!("{} to the other side.", y);
}
fn foo(mut bar: String) -> String {
bar.push_str("Break on through");
bar
}
fn main() {
let mut x = String::new();
foo(&mut x);
println!("{} to the other side.", x);
}
fn foo(bar: &mut String) -> () {
bar.push_str("Break on through");
}
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");
}
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!
}