You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I tried defining a generic closure in Rust like this:
letexample_closure<T> = |x:T| x;
However, this produces a compiler error: expected one of ':' , ';', '=', '@', or '|'. I understand that closures in Rust infer types based on their first use, but is there a way to explicitly make a closure generic without wrapping it in a function or struct? If not, could you explain why this limitation exists?
The text was updated successfully, but these errors were encountered:
Jeong-jin-Han
changed the title
[Assignment ?][11/13 Lecture Question] "Is it possible to define a generic closure in Rust?" - [Answer] Maybe Yes??
[Assignment ?][11/13 Lecture Question] "Is it possible to define a generic closure in Rust?" - [Answer] Maybe No??
Nov 13, 2024
Jeong-jin-Han
changed the title
[Assignment ?][11/13 Lecture Question] "Is it possible to define a generic closure in Rust?" - [Answer] Maybe No??
[Assignment ?][11/13 Lecture Question] "Is it possible to define a generic closure in Rust?"
Nov 13, 2024
There isn't. I'm not sure why it isn't supported, but my guess is that closures are typically single-use functions, so there is no real point on making it generic in the most case.
Also, generic code needs to be monomorphized at compile time, and it would be very difficult to account to do that for arbitrary let statements.
Related Issue
https://github.com/nrc/r4cppp/blob/master/closures.md
Googling Result
https://users.rust-lang.org/t/use-generics-in-closure/86679
ChatGPT Result
https://chatgpt.com/c/
Your question here
I tried defining a generic closure in Rust like this:
However, this produces a compiler error: expected one of ':' , ';', '=', '@', or '|'. I understand that closures in Rust infer types based on their first use, but is there a way to explicitly make a closure generic without wrapping it in a function or struct? If not, could you explain why this limitation exists?
The text was updated successfully, but these errors were encountered: