Skip to content

Commit aeedf22

Browse files
Add E0525 error explanation
1 parent 528c6f3 commit aeedf22

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/librustc/diagnostics.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1721,6 +1721,50 @@ fn cookie() -> ! { // error: definition of an unknown language item: `cookie`
17211721
```
17221722
"##,
17231723

1724+
E0525: r##"
1725+
A closure was attempted to get used whereas it doesn't implement the expected
1726+
trait.
1727+
1728+
Erroneous code example:
1729+
1730+
```compile_fail,E0525
1731+
struct X;
1732+
1733+
fn foo<T>(_: T) {}
1734+
fn bar<T: Fn(u32)>(_: T) {}
1735+
1736+
fn main() {
1737+
let x = X;
1738+
let closure = |_| foo(x); // error: expected a closure that implements
1739+
// the `Fn` trait, but this closure only
1740+
// implements `FnOnce`
1741+
bar(closure);
1742+
}
1743+
```
1744+
1745+
In the example above, `closure` is an `FnOnce` closure whereas the `bar`
1746+
function expected an `Fn` closure. In this case, it's simple to fix the issue,
1747+
you just have to implement `Copy` and `Clone` traits on `struct X` and it'll
1748+
be ok:
1749+
1750+
```
1751+
#[derive(Clone, Copy)] // We implement `Clone` and `Copy` traits.
1752+
struct X;
1753+
1754+
fn foo<T>(_: T) {}
1755+
fn bar<T: Fn(u32)>(_: T) {}
1756+
1757+
fn main() {
1758+
let x = X;
1759+
let closure = |_| foo(x);
1760+
bar(closure); // ok!
1761+
}
1762+
```
1763+
1764+
To understand better how closures work in Rust, read:
1765+
https://doc.rust-lang.org/book/closures.html
1766+
"##,
1767+
17241768
}
17251769

17261770

@@ -1760,5 +1804,4 @@ register_diagnostics! {
17601804
E0490, // a value of type `..` is borrowed for too long
17611805
E0491, // in type `..`, reference has a longer lifetime than the data it...
17621806
E0495, // cannot infer an appropriate lifetime due to conflicting requirements
1763-
E0525 // expected a closure that implements `..` but this closure only implements `..`
17641807
}

0 commit comments

Comments
 (0)