相关疑难解决方法(0)

无法摆脱借来的内容

我不明白这个错误cannot move out of borrowed content.我收到了很多次,我总是解决它,但我从来没有理解为什么.

例如:

for line in self.xslg_file.iter() {
    self.buffer.clear();

    for current_char in line.into_bytes().iter() {
        self.buffer.push(*current_char as char);
    }

    println!("{}", line);
}
Run Code Online (Sandbox Code Playgroud)

产生错误:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:31:33
   |
31 |             for current_char in line.into_bytes().iter() {
   |                                 ^^^^ cannot move out of borrowed content
Run Code Online (Sandbox Code Playgroud)

我通过克隆解决了这个问题line:

error[E0507]: cannot move out of `*line` which is behind a shared reference
  --> src/main.rs:31:33
   |
31 |             for current_char in line.into_bytes().iter() {
   |                                 ^^^^ …
Run Code Online (Sandbox Code Playgroud)

reference move-semantics rust borrow-checker

115
推荐指数
2
解决办法
6万
查看次数

闭包何时实现Fn,FnMut和FnOnce?

哪些具体条件为闭合来实现Fn,FnMutFnOnce特质?

那是:

  • 闭包什么时候没有实现这个FnOnce特性?
  • 闭包什么时候没有实现这个FnMut特性?
  • 闭包什么时候没有实现这个Fn特性?

例如,改变它的主体上的闭包状态会使编译器无法实现Fn它.

closures rust

97
推荐指数
2
解决办法
1万
查看次数

移动盒装函数时"无法移动FnOnce类型的值"

我正在尝试在Rust中进行一些高阶编程,但是我在处理闭包时遇到了一些困难.这是一个代码片段,说明了我遇到的一个问题:

pub enum Foo {
    Bar(Box<FnOnce(i32)>),
}

pub fn app(i: i32, arg: Foo) {
    match arg {
        Foo::Bar(f) => f(i),
    }
}
Run Code Online (Sandbox Code Playgroud)

当我编译这段代码时,我收到以下错误消息:

error[E0161]: cannot move a value of type std::ops::FnOnce(i32) + 'static: the size of std::ops::FnOnce(i32) + 'static cannot be statically determined
 --> src/main.rs:7:24
  |
7 |         Foo::Bar(f) => f(i),
  |                        ^
Run Code Online (Sandbox Code Playgroud)

因为我把函数放在一个Box,我会想到这将解决编译器不知道大小的问题.如何编译上述程序?

rust

10
推荐指数
1
解决办法
1877
查看次数