What is the difference between using a type as another name and a type alias?

What's the difference between

use hyper::status::StatusCode as Error; 

and

 type Error = hyper::status::StatusCode; 

Are there any differences between the two, besides the fact that type can also be pub type ? What are the benefits between using one or the other?

+7
rust
source share
1 answer

In the case of simple types, for example, in your example, the semantic difference does not exist. In addition, there is a direct analogue from use to pub type , it is pub use :

 // will be available to other modules pub use hyper::status::StatusCode as Error; 

However, there are differences in more complex cases. For example, you can define generic type aliases or aliases for specialized types:

 type Result<T> = ::std::result::Result<T, MyError>; type OptionI32 = Option<i32>; 

The general idea is that you usually use type aliases because they are more powerful and offer intent more clearly, for example using Result , and you use use .. as .. when you want to import only that name, but it conflicts with what is already in the current namespace:

 use std::io::Read as StdRead; trait Read: StdRead { ... } 

Note that using identifiers using a path should be preferable to renaming use . It is better to write the above as

 use std::io; trait Read: io::Read { ... } 

(unless, of course, the Read methods are not used for a particular type in a single file).

Using use .. as .. as a replacement for type (if possible) is unusual and I think it should be avoided.

+7
source share

All Articles