[英]Why can I move out of mutable self reference for Read?
我不明白為什么這段代碼可以編譯:
use std::io::{Read, BufRead};
trait ReadString {
fn read_null_terminated_string(&mut self, max_size: u64) -> std::io::Result<String>;
}
impl<R> ReadString for R
where
R: BufRead,
{
fn read_null_terminated_string(&mut self, max_size: u64) -> std::io::Result<String> {
let mut buf = Vec::new();
self.take(max_size).read_until(0, &mut buf)?;
Ok(String::from_utf8_lossy(&buf).to_string())
}
}
據我所知, BufRead
不是Copy
,而BufRead::take()
是:
fn take(self, limit: u64) -> Take<Self>
where
Self: Sized,
{
Take { inner: self, limit }
}
所以.take()
肯定應該移動self
,這是不允許的,因為我只有&mut self
? 我什至嘗試了我自己的BufRead
類特征,但我確實收到了這個錯誤:
cannot move out of `*self` which is behind a mutable reference
move occurs because `*self` has type `R`, which does not implement the `Copy` trait
那么,為什么BufRead
沒有出現該錯誤?
您不是在類型Self
上調用take()
,而是在類型&mut Self
( self
參數的類型)上調用它並且它確實使用了它。 這是有效的,因為Read
有一個全面的實現impl<R: Read +?Sized> Read for &mut R
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.