Skip to main content

Type Conversion in Rust

Type conversion is not special in Rust. It's just a function that takes ownership of the value and returns the other type. So you can name convert functions anything. However, it's a convention to use as_, to_, and into_ prefixed name or to use from_ prefixed constructor.

From

You can create any function for type conversion. However, if you want to provide generic interfaces, you'd better implement the From trait. For instance, you should implement From<X> for Y when you want the interface that converts the X type value to the Y type value.

The From trait have an associated function named from. You can call this function like From::from(x). You also can call it like Y::from(x) if the compiler cannot infer the type of the destination type.

Into

From have an associated function, it makes you be able to specify the destination type. It's why From has an associated function instead of a method, but on the other hands, you cannot use it as a method, like a.from().

You should implement the Into trait to use a method for type conversion. This trait allows a variable to be converted to another type with the method. You can use into as X::into(x) or Into::into, but no one needs to do it. It's merely a verbose code. Use x.into() as long as the compiler can infer the destination type. Otherwise, use From.

TryFrom

From and Into are traits to provide a conversion function that would not fail. However, some conversions can fail. For instance, converting from i128 to i32 can fail because some values of i128 are not in the range of i32. To do these conversions, you should use TryFrom and TryInto. For instance, Rust uses TryFrom that returns TryFromIntError on the failure for the above example.

TryInto

The relation between TryFrom and TryInto is the same as From and Into. TryFrom has an associated function named try_from and TryInto has a method named try_into.

From Implies Into

from and into should have the same behavior. The different behavior confuses the users; in fact, you cannot implement them differently. If you simultaneously implement From<Y> for X and Into<X> for Y, you would see the below error message.

error[E0119]: conflicting implementations of trait `std::convert::Into<X>` for type `Y`:

It's because From implies Into. It's called a blanket implementation.

Because of this blanket implementation, you'd better implement From instead of Into when you need a type converting method.

As far as I know, there is only one exception that you should implement Into instead of From. If the output type of the conversion function is a generic type that is not declared in the current crate, you cannot implement From. It's the only case(at least as far as I know). The same rule is applied to TryFrom and TryInto.

Comments

Popular posts from this blog

Understanding Aspect-Oriented Programming with Python Examples

Object-Oriented Programming (OOP) manages code by grouping it into independent modules known as objects, emphasizing the crucial principle of Separation of Concerns. This means each object should focus on its specific responsibilities. However, real-world applications often feature functionalities that are common across multiple objects or modules, such as logging, security, transaction management, and performance monitoring. These functionalities are called Cross-cutting Concerns. Challenge of Cross-Cutting Concerns Scattering These cross-cutting concerns, when handled solely with OOP, create two major problems. The first problem is Scattering , which is when code for a specific functionality is spread across multiple places through copying and pasting. For instance, imagine adding user permission checks and logging code to every function. The same logging and permission checking code would repeatedly appear within each method. Tangling The other issue is Tangling . This refe...

Cursor Movement with CSI Sequences

Code Abbr Name CSI # A CUU CUrsor Up CSI # B CUD CUrsor Down CSI # C CUF CUrsor Forward CSI # D CUB CUrsor Backward CSI # E CNL CUrsor Next Line CSI # F CPL CUrsor Previous Line CSI # I CHT Cursor Horizontal forward Tabulation CSI # Z CBT Cursor Backward Tabulation CSI # G CHA Cursor Horizontal Absolute CSI # ; # H CUP CUrsor Position Today, we will continue from the  previous article to explore how to move the cursor using CSI sequences. The types of CSI sequences for moving the cursor can be summarized as follows. CUU, CUD, CUF, CUB These are the abbreviations for CUrsor Up, CUrsor Down, CUrsor Forward, and CUrsor Backward; as the names suggest, they move the cursor up, down, forward, and backward. They take a single number as an argument; if the argument is omitted, it is treated as 1. Thus, 0x1b[A is equivalent to 0x1b[1A . In this case, CUF and CUB move only within the same line. In other words, CUB rece...

Iterator Adapters in Rust

An Iterator that takes another iterator and returns a new one is called an iterator adapter . The name "adapter" comes from one of the GoF's design patterns, the adapter pattern . However, in reality, it corresponds more to the decorator pattern , so if you pay too much attention to the name, you might get confused about its purpose. So it's better not to worry too much about the name. Enough complaining about the name, what does an iterator adapter do? An iterator adapter adds a task to be performed when the iterator iterates. This will be easier to understand when you see an example. The map function is one of the famous adapters. The iterator returned by the map function for those who have used functional languages iterates over new values transformed from the original values. Besides, various adapters are already implemented in the standard library. Among them, the most frequently used are those that are convenient to use with loops. Examples include the ...