1
0
Fork 0
mirror of https://github.com/rust-lang/rustlings.git synced 2024-05-10 12:36:09 +02:00
rustlings/exercises/23_conversions
Mo c7cf3720bd
Merge pull request #1799 from NicolasRoelandt/patch-1
Remove confusing aside in 23_conversions/from_str.rs
2024-03-27 17:28:35 +01:00
..
README.md Update Exercises Directory Names to Reflect Order 2023-10-16 07:37:12 -04:00
as_ref_mut.rs Update Exercises Directory Names to Reflect Order 2023-10-16 07:37:12 -04:00
from_into.rs Merge branch 'main' into main 2024-03-15 14:36:23 +01:00
from_str.rs Remove confusing aside in 23_conversions/from_str.rs 2023-12-08 17:52:21 +00:00
try_from_into.rs Update Exercises Directory Names to Reflect Order 2023-10-16 07:37:12 -04:00
using_as.rs Update Exercises Directory Names to Reflect Order 2023-10-16 07:37:12 -04:00

Type conversions

Rust offers a multitude of ways to convert a value of a given type into another type.

The simplest form of type conversion is a type cast expression. It is denoted with the binary operator as. For instance, println!("{}", 1 + 1.0); would not compile, since 1 is an integer while 1.0 is a float. However, println!("{}", 1 as f32 + 1.0) should compile. The exercise using_as tries to cover this.

Rust also offers traits that facilitate type conversions upon implementation. These traits can be found under the convert module. The traits are the following:

Furthermore, the std::str module offers a trait called FromStr which helps with converting strings into target types via the parse method on strings. If properly implemented for a given type Person, then let p: Person = "Mark,20".parse().unwrap() should both compile and run without panicking.

These should be the main ways within the standard library to convert data into your desired types.

Further information

These are not directly covered in the book, but the standard library has a great documentation for it.