rust - 将所有权移至 std::io::Chain

标签 rust lifetime ownership

我有一个 Readerer,我想在其中添加一些字节,创建一个 Chain。理想情况下,我想这样做:

use std::io::{Chain, Read};

fn thingify<R: Read>(r: R) -> Chain<[u8; 3], R> {
    let mut arr = [1u8, 2u8, 3u8];
    // Modify arr here
    return arr.chain(r);
}

但这会引发编译器错误:

error[E0308]: mismatched types
 --> test.rs:7:12
  |
3 | fn thingify<R: Read>(r: R) -> Chain<[u8; 3], R>
  |                               ----------------- expected `std::io::Chain<[u8; 3], R>` because of return type
...
7 |     return arr.chain(r);
  |            ^^^^^^^^^^^^ expected array of 3 elements, found &[u8]
  |
  = note: expected type `std::io::Chain<[u8; 3], _>`
             found type `std::io::Chain<&[u8], _>`

据我了解,这似乎是因为 Read 是针对切片而不是数组实现的,并且不知何故我的数组在这里衰减为切片。
但是,当我将返回类型中的数组更改为切片并为其赋予显式生命周期时:

use std::io::{Chain, Read};

fn thingify<'a, R: Read>(r: R) -> Chain<&'a [u8], R> {
    let arr = [1u8, 2u8, 3u8];
    // Modify arr here
    return arr.chain(r);
}

我只是得到另一个编译器错误:

error[E0515]: cannot return value referencing local variable `arr`
  --> test.rs:19:12
   |
19 |     return arr.chain(r);
   |            ---^^^^^^^^^
   |            |
   |            returns a value referencing data owned by the current function
   |            `arr` is borrowed here

如何将数组的所有权转移到 Chain 以便我可以归还它? [u8] 就不能做到这一点吗?

最佳答案

因为 Read &'_ [u8] 实现但不适用于 [u8; 3] ,编译器会自动将您的数组转换为引用切片。这意味着只要切片存在,您的数组就必须有效,只要 Chain 存在。直播。

有几种解决方案,你可以向调用者请求一个可变切片,你可以把它写成static如果你想改变它,如果你不想改变它,你也可以做到const ,如果你需要调整它的大小,你需要一个 Vec等等……

use std::io::{stdin, Chain, Read};

fn a<R: Read>(arr: &mut [u8; 3], r: R) -> Chain<&[u8], R> {
    arr.copy_from_slice(&[1, 2, 3]);
    arr.chain(r)
}

fn b<R: Read>(r: R) -> Chain<&'static [u8], R> {
    const ARR: [u8; 3] = [1, 2, 3];
    ARR.chain(r)
}

fn main() {
    let mut arr = [0; 3];
    println!("{:?}", a(&mut arr, stdin()));

    println!("{:?}", b(stdin()));
}

参见:

关于rust - 将所有权移至 std::io::Chain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158569/

相关文章:

static - 为什么 Rust 中的 const 函数不能调用关联函数?

rust - 通过局部生命周期来满足特质

c++ - 创建 "Handler Registration"类型架构时,我应该如何传递处理程序?

C++:访问 shared_ptr 的容器应该返回原始还是共享 ptr?

reference - 使用可变引用遍历递归结构并返回最后一个有效引用

rust - 如何使用以迭代器为参数的方法进行动态调度?

pointers - 使用rust 的生活

rust - 将 Rust 中的错误与特征对象生命周期混淆

rust - Rust中的 move 语义是什么?

rust - GitHub Actions 缓存 Rust 工件