Here is some functions to combine two things to one:
// It's right. move v1/v2's ownership in when call, move v's ownership back when finish.
fn combine_v(v1: Vec<i32>, v2: Vec<i32>) -> Vec<i32> {
let v = vec![1,2,3];
return v;
}
// It's right with lifetime statements. I can return a `&str` type var.
fn combine_s<'a>(s1: &'a str, s2: &'a str) -> &'a str {
let s = "123";
return s;
}
// It's not right.
fn combine<'a>(v1: &'a [i32], v2: &'a [i32]) -> &'a [i32] {
let a = [1, 2, 3];
// cannot return reference to local variable `a`
return &a;
}
// It's not right.
// Error: the size for values of type `[i32]` cannot be known at compilation time
fn combine_1(v1: [i32], v2: [i32]) -> [i32] {
let a = [1,2,3];
return a;
}
So I have questions:
Why you can return
&str
type but not a&[i32]
? Why&str
's value not dropped when function finish?(How) Can I write a function that accept
&[i32]
s, and return a new&[i32]
?(How) Can I write a function that accept
[i32]
s, and return a new[i32]
, when the length cannot be determined at compilation time?Why
[i32]
must have a length, but&[i32]
not?