]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0525.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0525.md
1 A closure was used but didn't implement the expected trait.
2
3 Erroneous code example:
4
5 ```compile_fail,E0525
6 struct X;
7
8 fn foo<T>(_: T) {}
9 fn bar<T: Fn(u32)>(_: T) {}
10
11 fn main() {
12     let x = X;
13     let closure = |_| foo(x); // error: expected a closure that implements
14                               //        the `Fn` trait, but this closure only
15                               //        implements `FnOnce`
16     bar(closure);
17 }
18 ```
19
20 In the example above, `closure` is an `FnOnce` closure whereas the `bar`
21 function expected an `Fn` closure. In this case, it's simple to fix the issue,
22 you just have to implement `Copy` and `Clone` traits on `struct X` and it'll
23 be ok:
24
25 ```
26 #[derive(Clone, Copy)] // We implement `Clone` and `Copy` traits.
27 struct X;
28
29 fn foo<T>(_: T) {}
30 fn bar<T: Fn(u32)>(_: T) {}
31
32 fn main() {
33     let x = X;
34     let closure = |_| foo(x);
35     bar(closure); // ok!
36 }
37 ```
38
39 To better understand how these work in Rust, read the [Closures][closures]
40 chapter of the Book.
41
42 [closures]: https://doc.rust-lang.org/book/ch13-01-closures.html