Why can't I compile this?
kang-sw opened this issue · comments
Seungwoo Kang commented
use once_cell::unsync::Lazy;
let lazy = Lazy::new(|| "sd".to_uppercase());
Above code returns following error:
error[E0282]: type annotations needed for `once_cell::unsync::Lazy<T, [closure@perfkit_config\src\storage.rs:65:31: 65:53]>`
--> perfkit_config\src\storage.rs:65:13
|
65 | let lazy = Lazy::new(|| "sd".to_uppercase());
| ^^^^
|
help: consider giving `lazy` an explicit type, where the type for type parameter `T` is specified
|
65 | let lazy: once_cell::unsync::Lazy<T, [closure@perfkit_config\src\storage.rs:65:31: 65:53]> = Lazy::new(|| "sd".to_uppercase());
| ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In Cargo:
[dependencies]
once_cell = "1.15.0"
(Can't compile example one neither, which replaces "sd" to captured 'hello')
It seems the compiler should deduce type 'String' from return value of given closure, but it doesn't. Am I doing something wrong?
I'm using rustc 1.63.0 on Windows.
Alex Kladov commented
Heh, that's an interesteen puzzle, see rust-lang/rust#103718.
We might consider doing the same for once cell, once our MSRV allows.
For your specific case, the fix would be
let lazy: Lazy<String, _> = Lazy::new(|| "sd".to_uppercase());
Seungwoo Kang commented
Oh, thanks for your reply. Now it compiles!