I am using rustc 1.70.1
I have a function which I thought would crash, but it doesn't:
fn testset<'a> () -> std::collections::HashSet<&'a i64> {
let mut set = HashSet::new();
set.insert(&123456);
set
}
fn main() {
let test = testset();
println!("{:?}", test);
}
Application output: {123456}
From my understanding, the 123456
only lives within the function, right? Shouldn't it "disappear" with the call stack of the function?
However, if I put the number as a variable, then pass the variable as a reference, I get the crash I expect:
fn testset<'a> () -> std::collections::HashSet<&'a i64> {
let mut set = HashSet::new();
let x = 123456;
set.insert(&x);
set
}
Compiler output:
error[E0515]: cannot return value referencing local variable `x`
--> src/main.rs:245:5
|
244 | set.insert(&x);
| -- `x` is borrowed here
245 | set
| ^^^ returns a value referencing data owned by the current function
For more information about this error, try `rustc --explain E0515`.
error: could not compile `radix-rust` (bin "radix-rust") due to previous error
I need help to understand what is happening here.