on-internet
← Community

Is this type-inference trick using undocumented/unspecified Rust semantics or is it fine?

Stack Overflow ·

Long time no see, StackOverflow! Context: I was writing a macro that deals with array literal syntax ([foo, bar, ...]) and emits vectors. I ran into the problem that empty arrays/vectors would lead to "type annotations required" errors. For my purpose the type of an empty vector didn't matter at all, so I just wanted it to default to (). I found this trick: trait OrUnit<T> {} impl<T> OrUnit<T> for u8 {} impl OrUnit<()> for i32 {} fn empty_vec<T, I: OrUnit<T>>(_: I) -> Vec<T> { Vec::new() } Using empty_vec(0) instead of vec![] falls back to () only if no type can be inferred otherwise. Lets tak

Comments

Sign in or sign up to comment and upvote.

No comments yet.