【问题标题】:Confusion about ownership/lifetime in Rust [closed]关于 Rust 中的所有权/生命周期的困惑 [关闭]
【发布时间】: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;
}

所以我有问题:

  1. 为什么你可以返回 &amp;str 类型而不是 &amp;[i32]?为什么&amp;str的值在函数完成时没有被丢弃?

  2. (如何)我可以编写一个接受&amp;[i32]s 并返回一个新的&amp;[i32] 的函数吗?

  3. (如何)如果在编译时无法确定长度,我能否编写一个接受[i32]s 的函数,并返回一个新的[i32]

  4. 为什么[i32] 必须有长度,而&amp;[i32] 没有?

【问题讨论】:

标签: rust


【解决方案1】:

以下是您的子问题的答案:

1) 为什么你可以返回&amp;str 类型而不是&amp;[i32]?为什么&amp;str的值在函数完成时没有被丢弃?

因为当您的代码编译时,它被称为'static 生命周期。因此,当函数完成时它不会被丢弃。

2) 如何编写一个接受&amp;[i32]s 的函数,并返回一个新的&amp;[i32]

您的函数的签名是正确的。但是在实现中,您需要使用'static 生命周期指定您的声明,或者至少以编译器可以将其引用为'static 的方式编写它。 Reference

3) 当编译时无法确定长度时,如何编写一个接受[i32]s 的函数,并返回一个新的[i32]

如需使用它们,您需要使用 Box 并更改您的函数签名,如下所示:Reference

fn combine_1(v1: Box<[i32]>, v2: Box<[i32]>) -> Box<[i32]>

4) 为什么[i32] 必须有长度,而&amp;[i32] 没有?

Rust 中基本上有 2 种形式的数组:Reference

  • [T; N]NTs的数组,它是Sized
  • [T]T 的数组,其大小仅在运行时知道,它不是 Sized,并且只能作为切片 (&amp;[T]) 进行操作。

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多