What is the difference between
use hyper::status::StatusCode as Error;
and
type Error = hyper::status::StatusCode;
Are the any more differences between them except that type
can be also pub type
? What are the benefits between using one or another?
A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.
“One difference is, that interfaces create a new name that is used everywhere. Type aliases don't create a new name — for instance, error messages won't use the alias name.”
A type alias is basically a name for any type. Type aliases can be used to represent not only primitives but also object types, union types, tuples and intersections.
You can use an alias declaration to declare a name to use as a synonym for a previously declared type. (This mechanism is also referred to informally as a type alias). You can also use this mechanism to create an alias template, which can be useful for custom allocators.
In case of simple types, like in your example, there doesn't seem to be any semantic difference. Moreover, there is a direct analogue with use
to pub type
, it's 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 generic 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 suggest the intent more clearly, like with Result
, and you use use .. as ..
when you only want to import that specific name but it conflicts with something which is already in the current namespace:
use std::io::Read as StdRead;
trait Read: StdRead { ... }
Note that using path-qualified identifiers should be preferred to use
renaming. The above is better written as
use std::io;
trait Read: io::Read { ... }
(unless Read
methods are used for some concrete type in the same file, of course).
Using use .. as ..
as a substitute for type
(in case where it is possible) is uncommon and I think it should be avoided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With