Is it possible to implement methods for type aliases?

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 determine the intrinsic impl for a type outside the box where the type is specified; define and implement a character or a new type instead

I was able to find others who had the same problem back in February , but at that time there was no solution.

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

+8
source share
1 answer

Is there any fix

Not really. A type alias ( type Foo = Bar ) does not create a new type. All he does is create another name that references an existing type.

In Rust, you are not allowed to implement built-in methods for a type obtained from another mailbox.

another way for me to implement

The usual solution is to create a new type. In fact, this is called newtype !

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

There is no lack of runtime - both versions will occupy the same amount of space. In addition, you will not accidentally expose any methods that you did not want. For example, do you really want your code clients to call Option::take ?

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

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

LinkMethods here is that to invoke these LinkMethods methods a LinkMethods present. You also cannot implement a trait that you do not own for a type that does not belong to you.

See also:

+19
source

Source: https://habr.com/ru/post/1243628/


All Articles