Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 644
Victor Polevoy Avatar asked Jun 28 '16 09:06

Victor Polevoy


People also ask

What is a type alias?

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.

What is the difference between type alias and interface?

“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.”

What is a type alias Javascript?

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.

What is an alias in C++?

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.


1 Answers

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.

like image 173
Vladimir Matveev Avatar answered Oct 27 '22 20:10

Vladimir Matveev