Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Assignment ?][11/13 Lecture Question] "Is it possible to define a generic closure in Rust?" #424

Open
Jeong-jin-Han opened this issue Nov 13, 2024 · 2 comments
Assignees
Labels
question Further information is requested

Comments

@Jeong-jin-Han
Copy link

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:

let example_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?

@Jeong-jin-Han Jeong-jin-Han added the question Further information is requested label Nov 13, 2024
@Jeong-jin-Han 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 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
@Lee-Janggun
Copy link
Member

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.

@Jeong-jin-Han
Copy link
Author

Thank you!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants