Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement methods on type aliases?

Tags:

rust

Consider the following implementation:

pub struct BST {     root: Link, }  type Link = Option<Box<Node>>;  struct Node {     left: Link,     elem: i32,     right: Link, }  impl Link { /* misc */ }  impl BST { /* misc */ } 

I keep getting the error:

cannot define inherent impl for a type outside of the crate where the type is defined; define and implement a trait or new type instead

I was able to find others had this same issue back in February, but there was seemingly no solution at the time.

Is there any fix or another way for me to implement my Link typedef in Rust?

like image 793
SantiBuenahora Avatar asked Feb 23 '16 04:02

SantiBuenahora


People also ask

For what do we use type aliases?

Type aliases allow you to create a new name for an existing type.

What is type keyword in Rust?

The type keyword in rust has a different meaning in the 2 places it can be used: Type alias: Just another name for the same type. Associated types: this occurs within traits and trait impl blocks.

What are rust traits?

A trait in Rust is a group of methods that are defined for a particular type. Traits are an abstract definition of shared behavior amongst different types. So, in a way, traits are to Rust what interfaces are to Java or abstract classes are to C++. A trait method is able to access other methods within that trait.


1 Answers

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?
like image 100
Shepmaster Avatar answered Oct 19 '22 12:10

Shepmaster