- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
trait Output {
fn write(&mut self, text: &str);
}
struct DummyOutput {}
impl Output for DummyOutput {
fn write(&mut self, text: &str) {
// self does not need to be mut in this reproducer,
// but it would in the real version
println!("{}", text);
}
}
enum EncoderOutput<'a, T> {
Owned(T),
Borrowed(&'a mut T),
}
impl<'a, T> AsMut<T> for EncoderOutput<'a, T> {
fn as_mut(&mut self) -> &mut T {
match self {
EncoderOutput::Owned(ref mut o) => o,
EncoderOutput::Borrowed(b) => b,
}
}
}
struct Encoder<'a, O: Output> {
output: EncoderOutput<'a, O>,
}
impl<'a, O: Output> Encoder<'a, O> {
// here's the idea:
// every child instance will have a borrowed output,
// and always only one level of indirection, i.e.:
// - root: "&mut O" or "O"
// - child1: "&mut O"
// - child2: "&mut O"
// but never:
// - childN: "&mut &mut O"
fn child(&'a mut self) -> Self {
Encoder {
output: EncoderOutput::Borrowed(self.output.as_mut()),
}
}
}
fn main() {
let mut enc1 = Encoder {
output: EncoderOutput::Owned(DummyOutput {}),
};
{
// I know this borrows mutably from enc1
let mut enc2 = enc1.child();
// so this will obviously not work:
// enc1.output.as_mut().write("bar 2b");
// but this does work:
enc2.output.as_mut().write("bar 2a");
} // but then the borrow "enc2" should be dropped here?
// so why does this fail with:
// "cannot borrow [...] as mutable more than once"
enc1.output.as_mut().write("bar 3");
}
error[E0499]: cannot borrow `enc1.output` as mutable more than once at a time
--> src/main.rs:68:5
|
57 | let mut enc2 = enc1.child();
| ---- first mutable borrow occurs here
...
68 | enc1.output.as_mut().write("bar 3");
| ^^^^^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
我的直觉告诉我这失败了,因为
Encoder
返回的
child()
中借用的有效期与“父”的有效期相同-但我看不到解耦有效期的方法,即使返回的值显然应该有一个生命周期比父项短或相等,因为它可以事先删除。
EncoderOutput
的版本,只是直接在
&mut O
中有一个
Encoder
,但是问题是相同的。
main()
中的作用域结束时,会删除
enc2
,并运行隐式的
Drop
impl,这会清理
EncoderOutput::Borrowed
和其中的引用,因此不会将其他
&mut
ref保留给
enc1
和
enc1
可以再次可变地借用。
最佳答案
改变:
fn child(&'a mut self) -> Encoder<'a, O>;
到:
fn child(&mut self) -> Encoder<'_, O>;
固定的编译示例:
trait Output {
fn write(&mut self, text: &str);
}
struct DummyOutput {}
impl Output for DummyOutput {
fn write(&mut self, text: &str) {
println!("{}", text);
}
}
enum EncoderOutput<'a, T> {
Owned(T),
Borrowed(&'a mut T),
}
impl<'a, T> AsMut<T> for EncoderOutput<'a, T> {
fn as_mut(&mut self) -> &mut T {
match self {
EncoderOutput::Owned(ref mut o) => o,
EncoderOutput::Borrowed(b) => b,
}
}
}
struct Encoder<'a, O: Output> {
output: EncoderOutput<'a, O>,
}
impl<'a, O: Output> Encoder<'a, O> {
// line below changed from:
// fn child(&'a mut self) -> Encoder<'a, O> {
// to:
// child(&mut self) -> Encoder<'_, O> {
fn child(&mut self) -> Encoder<'_, O> {
Encoder {
output: EncoderOutput::Borrowed(self.output.as_mut()),
}
}
}
fn main() {
let mut enc1 = Encoder {
output: EncoderOutput::Owned(DummyOutput {}),
};
{
let mut enc2 = enc1.child();
enc2.output.as_mut().write("bar 2a");
}
enc1.output.as_mut().write("bar 3");
}
playground
&'a self
和
&'a mut self
是所有Rust中最常见的生存陷阱,大多数初学者甚至中级Rustaceans最终都会陷入其中。我知道您的示例中的第二行是错的,甚至没有尝试去理解其余代码的其他内容。超过99.9%的时间
&'a self
和
&'a mut self
是错误的,只要您看到两者中的任何一个,它都应该发出一个大的红色标记,当您看到它们时,应该积极地重构它们。好的,顺便说一句,这就是它们如此糟糕的原因:
Container<'a>
,那么该容器的生命周期是多少?它的生命周期与引用生命周期相同,因为容器不能超过其所包含的生命周期。让我们将其称为生命周期
'a
。非常重要:
'a
中的
Container<'a>
代表了容器的整个生命周期。因此,当您使用
&'a self
或
&'a mut self
接收器编写方法时,与编译器通信的内容是“为了调用此方法,该方法必须在整个生命周期的剩余时间内借用该容器”。现在,您真正想要的是什么时候?几乎从不!极少需要编写一个只能被调用一次的方法,因为它在
self
的整个生命周期中都永久借用了
self
。 Ergo,
&'a self
和
&'a mut self
是新手陷阱,请避免使用它们。
&'a self
代表
&'a mut self
本身的整个生命周期时,
'a
和
self
只是红色标记。在以下情况下,
'a
仅限于单个方法,那么就可以了:
// 'a only local to this method, this is okay
fn method<'a>(&'a self) {
// etc
}
关于generics - “cannot borrow as mutable more than once”,即使是在放弃第一次借阅后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66104335/
在文档中指出 impl Borrow for T where T: ?Sized, 我会读这个: This Trait is implemented for every Type, even
This question already has answers here: How to lookup from and insert into a HashMap efficiently? (2
在这种情况下,错误是什么意思: fn main() { let mut v: Vec = vec![1, 2, 3, 4, 5]; v[v[1]] = 999; } error[E05
我有以下代码(仅作为示例),无法满足借阅检查器的要求。 一种方法修改struct的一个字段,然后调用另一种方法修改另一个字段。问题是调用第二个方法时,它需要一个依赖于该结构的参数。调用second方法
我在借用检查器没有“释放”可变借用时遇到问题。 我有: let mut data = (1..=100).collect::>(); let mut c = Canvas::new(10, 10, &
我在 Rust 1.6.0 中有一个 JSON 编码的对象。我想从 JSON 解码它,更改一个键的值,然后再次将其转换回 JSON 编码的字符串。我不想编写结构来保存数据。 我正在使用 rustc_s
这个问题在这里已经有了答案: What are non-lexical lifetimes? (1 个回答) Moved variable still borrowing after calling
这个问题在这里已经有了答案: What are non-lexical lifetimes? (1 个回答) Moved variable still borrowing after calling
在这种情况下,错误意味着什么: fn main() { let mut v: Vec = vec![1, 2, 3, 4, 5]; v[v[1]] = 999; } error[E05
为什么我不能在 inspect 期间push 到这个 vector 并在 skip_while 期间对其执行contains? 我已经为自己的结构 Chain 实现了自己的迭代器,如下所示: stru
我正在尝试实现一个将产生质数的迭代器。我将已经找到的质数存储在 Vec 中. 这是我的实现: struct Primes { primes: Vec, } impl Primes {
let mut map: HashMap = HashMap::new(); for (i, c) in text.chars().enumerate() { if map.contains_
此代码使用帕斯卡三角形的模数计算组合。 MUsize 是一个在操作中自动求模的结构。 当我运行实现运算符重载的特征存储结构时,出现错误。 当我使用 usize 而不是 MUsize 时,不会出现此警告
我想创建一个使用异步 IO 的 SOCKS5 代理的变体。我以前在 Haskell 中做过这个,所以我认为这将是一个很好的学习挑战。我从非常 well-documented SOCKS5 exampl
在一个函数内,我试图将一个值压入一个向量,然后返回对该值的引用,该值位于该向量内。遗憾的是,它不起作用,我收到以下错误: error[E0502]: cannot borrow `vector` as
我正在编写一个小程序来识别字符串中第一个重复出现的字符: use std::io; fn main() { let mut main_string = String::new(); p
学习了一段时间的Rust,我开始以为我理解了它的所有权/借用机制,但是接下来的例子让我真的很疑惑。我在玩 rust-sdl2 : extern crate sdl2; use sdl2::Sdl; u
这个问题在这里已经有了答案: What are the options to end a mutable borrow in Rust? (1 个回答) 关闭 5 年前。 我正在尝试在 Rust 中
我想将HashSet [0]的元素移动到HashSet [1]: 项目1:直接将remove()插入() 错误,无法满足。 use std::collections::HashSet; fn main
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
我是一名优秀的程序员,十分优秀!