Implicit vs explicit "into"

Viewed 442

So I've noticed there are multiple ways to convert from &str to String, but (for the sake of my question) I'll only talk about two ways, which would be "foo".to_string() and "foo".into(). Now I know that those are fundamentally different. The first of those is a method, while the second one is a trait-(implementation).

I currently need a piece of code that converts a ObjectNode into a Node.

First I implemented this using the Into trait:

struct ObjectNode {}

impl Into<Node> for ObjectNode {
    fn into(self) -> Node {
        Node::Object(self)
    }
}

enum Node {
    Object(ObjectNode)
}

But then I noticed that I had used "foo".to_string() instead of "foo".into() in my code. Simple because that's the thing I read online in pieces of code by other people. So I thought about implementing:

impl ObjectNode {
    fn into_node(self) -> Node {
        Node::Object(self)
    }
}

I'm now wondering if this "explicit" into_node method is somehow preferred over the "implicit" into, as into could be implemented for quiet a large number of types (which could lead to some... unexpected behavior, maybe?). Or maybe it's better to do it the other way around?

1 Answers

Well I guess you should implement From<ObjectNode> for Node rather than implementing Into<Node> for ObjectNode because the standard library for Into highlights it:-

One should avoid implementing Into and implement From instead. Implementing From automatically provides one with an implementation of Into thanks to the blanket implementation in the standard library.

You should probably go for an implementation of From rather than creating a separate method for converting it. Most crates in the Rust ecosystem heavily depend on these functions for their type conversions.

Related