是否可以获取变量的可变所有权?如果可以,如何获取?这是我的意思的一个例子(它不能编译):
fn read_all_input<I: Iterator<u8>>(dont_use_after: mut I) -> SuperReturn {
//This function will consume all the iterator and therefore wants to TAKE it away
//from the user, not borrow it.
}
fn main() {
//Somehow get an iter.
let mut myIter = ...;
//Pass it to the function.
read_all_input(myIter);
//Make the compiler cry here.
let x = myIter.next();
}
我知道我可以采用可变引用,但我更愿意将迭代器移动到函数中并进行可变操作(for 循环当然需要可变迭代器)。
谢谢, 菲尔
最佳答案
你快明白了。签名应为:
fn read_all_input<I: Iterator<u8>>(mut dont_use_after: I) -> SuperReturn {
// ^^^
继承的可变性发生在绑定(bind)/模式上,而不是类型上。 &mut T
中有一个 mut
,因为那里的可变性不是继承的。
关于rust - 可变地获取函数中变量的所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25939463/