4 ms·
It would probably be more clear if the type was specified here instead of letting the compiler infer it.
by aliasxneo 4y ago
It would probably be more clear if the type was specified here instead of letting the compiler infer it.
- andrewaylett 4y agoIf it's not clear that the compiler will infer the correct type, you can be specific. From the context, there's only one possible type though so that's redundant. Unlike C, older C++, or older Java, Rust expressions aren't necessarily fully typed in isolation. It's quite normal for a function to have an independently-generic return type and for the final type to be provided solely by context. Type inference only happens within named functions though: you need to specify your function signature. Even if you find yourself wanting to know what the type actually is, the compiler (in its guise as a language server) can tell you that and let your IDE show you, rather than requiring you to type it out yourself.
- aliasxneo 4y agoAbsolutely, I would have done the same in my code, I was more referring to the fact that sometimes it's helpful to be explicit when targeting a novice audience.
- jamincan 4y agoThe only way I can figure out to make this explicit, though, seems very verbose and non-intuitive and frankly no clearer than `.into()` on its own: Err(Into::<Box<dyn Error>>::into("sha1 hash is not valid")) Is there a better way to constrain the trait implementation of Into?
- andrewaylett 4y agoYou can (although I wouldn't recommend it) be explicit about the type using 'as': Err("sha1 hash is not valid".into()) as Result<(), Box<dyn Error>> Or I'd often reach for an intermediate variable before a turbofish: let e: Box<dyn Error> = "".into(); Err(e) The 'as' trick is useful for helping the compiler to understand the return of a lambda where you need it to coerce errors to a specific type.