3 ms·
> When would I use Into, when From The standard library contains this code: // From implies Into #[stable(feature = "rust1", since = "1.0.0")] imp
by steveklabnik 12y ago
> When would I use Into, when From
The standard library contains this code:
// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
fn into(self) -> U {
U::from(self)
}
}
So, you basically only ever implement From, and you get the equivalent Into for free.
More specifically, you would usually use `Into` to bound a generic function:
fn is_hello<T: Into<Vec<u8>>>(s: T) {
let bytes = b"hello".to_vec();
assert_eq!(bytes, s.into());
}
let s = "hello".to_string();
is_hello(s);
Whereas you'd use From to perform a conversion:
let string = "hello".to_string();
let other_string = String::from("hello");
assert_eq!(string, other_string);
These APIs are pretty new; they landed _right_ before beta happened. We used to have FromFoo traits, and this generic system replaced them.
- rbalicki 12y agoThank you! This is the best explanation I've been able to find for how to use From, instead of Into. One thing that's useful about From is that you can implement From<SomePublicStruct> for YourPrivateStruct, but the compiler complains about Into<YourPrivateStruct> for SomePublicStruct. SomePublicStruct could be (i32, i32) and YourPrivateStruct could be MyPoint, for example. Making YourPrivateStruct public (with pub struct) fixes things, but that's not always what you want.
- steveklabnik 12y agoAny time. I myself checked in with IRC as I posted. :) Like I said, these traits are really new, and so they don't have great docs yet...
- jimmyhmiller 12y agoMaybe a bit off topic. I've always heard that traits in rust are basically just type classes in haskell. But I'm not quite sure how you would implement this trait as a typeclass. Specifically, from what I'm seeing here is that if you just implement From you've also now implemented Into. Is there an analog in haskell? I also can't figure out how to specify a type class that is parametrized the way into is. Can anyone help by shedding some light on how you might go about this in haskell? Or where traits in rust differ from typeclasses in haskell?
- rapala 12y agoStandard Haskell has only single parameter type classes. With MultiParamTypeClasses you can define class Into a b where into :: a -> b Note that From would be the exact same class. I guess the distinction in Rust is relevant because of ownership.