0

Why can I create a reference to an object created inside a function without first copying it to some variable? Isn't the object dropped at the end of the function?

struct MyStruct {
    one: i32
}

fn main() {
    let result: &String = &return_value();
    println!("{result}");
    
    let result2: &MyStruct = &return_struct();
    println!("{}", result2.one);
    
    let result3: &String = &return_concatenate(String::from("Hi"));
    println!("{result3}");
}

fn return_value() -> String {
    String::from("Hi!")
}

fn return_struct() -> MyStruct {
    MyStruct {
        one: 1
    }
}

fn return_concatenate(mut s: String) -> String {
    s.push_str("!!!");
    s
}
FeliceMente
  • 263
  • 1
  • 3
  • 8

0 Answers0