4 ms·
Is there a way to ask Rust to tell me the type of an expression like `foo.iter().map(...).filter(...).step(...).take(...)`? I often feel very much in the dark a
by hathawsh 7y ago
Is there a way to ask Rust to tell me the type of an expression like `foo.iter().map(...).filter(...).step(...).take(...)`? I often feel very much in the dark about Rust types and some kind of command to show me Rust's interpretation of the type of an expression in context might help a lot.
- oconnor663 7y agoThe hack that I've seen people use the most is to write a line like this: () = foo; Then rustc will print out an error that includes the type of `foo`.
- hathawsh 7y agoNice, thanks!
- danbolt 7y agoScott Meyers also suggests the same sort of thing in Effective Modern C++ when not using an IDE. Personally, I use the technique a lot for debugging template errors in the language.
- stochastic_monk 7y agoSpecifically: template<typename T> struct TD; Instantiate this as ‘TD<decltype(foo)>’ to get the full name of the type. Rust’s does seem more concise.
- edflsafoiewq 7y agoNote that you don't get the full name of the type with a bad assignment in Rust, you only get the part of the type that was deduced before type checking failed. A generic type might have undeduced blanks, eg. Vec<_>. A side-effect of type inference.
- pc2g4d 7y agoJust try assigning the expression to a variable of definitely the wrong type, and the compiler will print out the full type in the error message, e.g. let x: () = foo.iter().map(...).filter(...).step(...).take(...);
- slaymaker1907 7y agoIn VSCode, you can assign it to a variable and then mouse over to see what type it infers.
- umanwizard 7y agoThis usually works, but type inference in RLS (or Rust-Analyzer) breaks often enough that it's not a complete solution.
- Matthias247 7y agoIntelliJ shows the inferred types by default. However it Gasversorgung it’s limitations with complex Rust types.
- umanwizard 7y ago> However it Gasversorgung it’s limitations I guess this is some autocorrect error? What did you mean to say?
- Matthias247 7y agoOh wow, I just saw that now. It was certainly autocorrect on phone. Should only have been "has". If you are curious: Gasversorgung would be be "gas supply".
- umanwizard 7y agolet _ = 5 + foo.iter().bar().quux().asdf(); The compiler will now tell you that <your type> cannot be added to an `i32`.
- tsbinz 7y agoIn the old days in C++ we'd try to assign it to int and look at the compiler error message. (That literally was the instruction of how to figure out the type to use in one of boost's libraries in pre-c++11 times ...)