by nailer · 4y ago · 0 comments
Not asking for an answer just pointing out that’s not a very useful name.
This is a "not very useful name" because it is a very generic (and core) trait. https://doc.rust-lang.org/std/convert/trait.Into.html This is the standard interface for converting anything into anything.
The way this is often used relies on type-inference. In this case it is being used as `return Err("sha1 hash is not valid".into())` inside a function that returns `Result<(), Box<dyn Error>>`. This means that the expression is inferred to evaluate to a `Box<dyn Error>`. Luckily there is an implementation of the Into trait for &str to that type (https://doc.rust-lang.org/std/convert/trait.From.html#impl-F...). So `.into()` just does the right thing.
This is a less common use case but the most common one I see is:
let s: String = "foobar".into()
Which converts a &'static str to a String.It sounds like it should be called .intoType() or .fixType() (it seems to use the compiler to work out the specific type) but again I don’t care about the answer I’m merely commenting that it’s not evident from reading the code as someone that knows a few languages.
https://doc.rust-lang.org/rust-by-example/conversion/from_in...
You got me there, smartypants. What my whole argument was hinging on.
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.
Err(Into::<Box<dyn Error>>::into("sha1 hash is not valid"))
Is there a better way to constrain the trait implementation of Into?
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.