rust - 为什么从 Rust 中的函数返回一个 &[u8] 而不是 u8 借用自己?

标签 rust borrow-checker borrowing

我有以下代码

pub struct Something {
    value: usize,
}

impl Something {
    pub fn get_and_increment(&mut self) -> &[u8] {
        let res = self.get();
        self.value += 1;

        res
    }

    pub fn get(&self) -> &[u8] {
        &[3; 2]
    }
}

当我尝试编译这个时,我得到了这个错误:

error[E0506]: cannot assign to `self.value` because it is borrowed
 --> src/main.rs:8:9
  |
7 |         let res = self.get();
  |                   ---- borrow of `self.value` occurs here
8 |         self.value += 1;
  |         ^^^^^^^^^^^^^^^ assignment to borrowed `self.value` occurs here

如果我将每个函数的返回类型更改为 u8 而不是 &[u8] 它编译得很好:

pub struct Something {
    value: usize,
}

impl Something {
    pub fn get_and_increment(&mut self) -> u8 {
        let res = self.get();
        self.value += 1;

        res
    }

    pub fn get(&self) -> u8 {
        3
    }
}

为什么 Rust 不允许我在 self 之后的 get_and_increment 函数中使用 Somethingvalue 属性。 get 被调用但仅当两个函数都返回 &[u8]?

最佳答案

我强烈建议返回并重新阅读 The Rust Programming Language ,特别是关于references and borrowing的章节.

Why does returning a &[u8] rather than u8 from a function in Rust borrow self?

本质上在问

why does returning «something that is borrowed» rather than «something that is not borrowed» from a function «require a borrow»?

遗憾的回答是:因为u8不是借来的,而&[u8]是借来的。

Why is it that Rust doesn't let me use the value property

因为在检查 get_and_increment 的主体时,编译器不知道 self 的哪些值作为 get 的一部分返回。您的 get 实现完全有可能返回对 value 的引用,或者将来可能,因此编译器必须采取保守的方式路由并禁止它。

but only when both functions return &[u8]?

这是不准确的。 get_and_increment 的返回类型对错误没有影响。 get 的返回类型仅在它包含引用时才重要。


然而,您没有明显的理由返回引用:

pub fn get(&self) -> [u8; 2] {
    [3; 2]
}

如果你出于某种原因想要返回一个引用,它不需要绑定(bind)到 self 的生命周期(你的代码因为 lifetime elision ):

pub fn get(&self) -> &'static [u8] {
    &[3; 2]
}

另见:

关于rust - 为什么从 Rust 中的函数返回一个 &[u8] 而不是 u8 借用自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777187/

相关文章:

windows - 无法在 Windows 上使用 Rust 和 GTK 运行 pkg-config

rust - 如何使用 Rust 浏览 OPC UA 服务器的节点?

rust - 为什么不能在同一结构中存储值和对该值的引用?

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

rust - 如何使用 Rust 类型系统来防止输出到标准输出?

rust - 创建拥有一些中间数据并指向它的迭代器的惯用方式是什么?

rust - 在等待读取时处理写入 TcpStream 的惯用方法

rust - 如何将具有 `Read`特征的字符串形式的东西传递给 `From`的实现?

rust - 如何为包含原始指针的结构强制执行生命周期?

rust - Rust 中的多重可变引用预防是如何工作的?