Is it possible to implement methods on type aliases?

后端 未结 1 547
孤独总比滥情好
孤独总比滥情好 2020-11-29 10:25

Consider the following implementation:

pub struct BST {
    root: Link,
}

type Link = Option>;

struct Node {
    left: Link,
    elem         


        
相关标签:
1条回答
  • 2020-11-29 10:50

    Is there any fix

    Not really. A type alias (type Foo = Bar) does not create a new type. All it does is create a different name that refers to the existing type.

    In Rust, you are not allowed to implement inherent methods for a type that comes from another crate.

    another way for me to implement

    The normal solution is to create a brand new type. In fact, it goes by the name newtype!

    struct Link(Option<Box<Node>>);
    
    impl Link {
        // methods all up in here
    }
    

    There's no runtime disadvantage to this - both versions will take the exact same amount of space. Additionally, you won't accidentally expose any methods you didn't mean to. For example, do you really want clients of your code to be able to call Option::take?

    Another solution is to create your own trait, and then implement it for your type. From the callers point of view, it looks basically the same:

    type Link = Option<Box<Node>>;
    
    trait LinkMethods {
        fn cool_method(&self);
    }
    
    impl LinkMethods for Link {
        fn cool_method(&self) {
            // ...
        }
    }
    

    The annoyance here is that the trait LinkMethods has to be in scope to call these methods. You also cannot implement a trait you don't own for a type you don't own.

    See also:

    • How do I implement a trait I don't own for a type I don't own?
    0 讨论(0)
提交回复
热议问题