“This is the 18th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”


This particular feature of Rust is one THAT I often see in the Bevy sample code, especially when it comes to colors, such as:

materials.add(Color::rgb(0.7.0.7.0.7).into())
Copy the code

I thought about it a lot, but I was finally able to figure out what it did Well, at least I think I do.

as

Simple (explicit) type conversions or casting in Rust can be done with the AS keyword:

fn main() {
  let num:u8 = 10;
  let multiplied = times_ten(num as f32);

  println!("{}", multiplied); / / 100
}

fn times_ten(val: f32) - >f32 {
  val * 10.0
}
Copy the code

From

In Rust, From is one of two traits that are converted to type.

Suppose I wanted to create my own special type, called MySpecialNumber, and wanted to convert an existing U32 variable to my custom type, I would do it like this:

#[derive(Debug)] // needed because struct displays nothing so needs to have a debug view
struct MySpecialNumber(u32);

impl From<u32> for MySpecialNumber {
  fn from(num: u32) - >Self {
    MySpecialNumber(num)
  }
}

fn main() {
  let existing_var = 30;
  let num = MySpecialNumber::from(existing_var);
  println!("{:? }", num); // Prints -> MySpecialNumber(30)
}
Copy the code

If this is the first time you’ve seen the struct or IMPl keyword again, don’t worry. I plan to cover these in a future article. But if you come from Javascript, you can think of them as a slightly more sophisticated way of making objects.

The code fragment above uses the from() written above to change the EXISTing_var of type U32 to the MySpecialNumber type.

Because the From method extends a trait, it must be written in a very special way to work. If I change the fn from(num: u32) line to fn from(num: f32), it won’t work. The source code for the From trait can be found at the Rust Github repo.

Into

Into is the second trait in Rust used for type conversion. It works in the opposite direction of the From trait, instead of creating x From Y, it converts y to X. Does that make sense? It’s a little confusing. I think code is the best way to explain things.

First way

If you already have an implementation of the From trait, you can also use Into trait, which is handy.

To use into, the main function of the code snippet above can be rewritten as:

.fn main() {
  let existing_var: u32 = 30;
  let num: MySpecialNumber = existing_var.into();
  println!("{:? }", num); // Prints -> MySpecialNumber(30)
}
Copy the code

It’s arguably more readable. Existing_var is converted to MySpecialNumber because it is added with a type annotation. If this type token is removed, Rust will not know what type to convert an existing variable to.

let num = existing_var.into(); // this won't work
Copy the code

If you really want to, you can write a full Into method with the Into method in Rust source code, similar to the From method I wrote above, but I think From is good enough.