rust - 可变地获取函数中变量的所有权

标签 rust

是否可以获取变量的可变所有权?如果可以,如何获取?这是我的意思的一个例子(它不能编译):

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/

相关文章:

rust - 引用内部闭包的迭代器的智能构造函数

rust - 如何在 `cargo doc`生成的文档中获取功能需求标签?

rust - 闭包生命周期问题

rust - 对于实现相同特征的结构,如何克服具有不兼容类型的匹配臂?

regex - 正则表达式删除整行

rust - 为什么 Rust 找不到 wl_display_get_registry?

rust - fold 对它接受的闭包很挑剔

rust - 字符串连接错误 : expected a literal

rust - 可中止 : Dangling Futures?

c - 如何使用 MSVC 在 Windows 上针对 "cdylib"Rust lib 编译+链接一个简单的 hello_world.c