【发布时间】:2019-04-03 06:40:18
【问题描述】:
以下是一些将两件事合二为一的功能:
// 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;
}
所以我有问题:
为什么你可以返回
&str类型而不是&[i32]?为什么&str的值在函数完成时没有被丢弃?(如何)我可以编写一个接受
&[i32]s 并返回一个新的&[i32]的函数吗?(如何)如果在编译时无法确定长度,我能否编写一个接受
[i32]s 的函数,并返回一个新的[i32]?为什么
[i32]必须有长度,而&[i32]没有?
【问题讨论】:
-
一个问题有这么多问题
-
@Stargateur 我会分解成几个小问题
标签: rust