This repository has been archived on 2023-03-24. You can view files and clone it, but cannot push or open issues or pull requests.
rustlings-exercises-completed/exercises/conversions
Tonći Galić dab90f7b91
Remove duplicate not done comment
As indicated in #259 , I found it confusing to have 2 comments as the code wouldn't compile unless I solved both issues (I used the script from #281 to remove a comment and use `:wn` to go to next exercise, hence this tripped me).
2020-04-07 17:00:45 +02:00
..
as_ref_mut.rs Remove duplicate not done comment 2020-04-07 17:00:45 +02:00
from_into.rs adds additional test to meet exercise rules 2020-03-11 07:58:04 -07:00
from_str.rs I AM NOT DONE comment in conversions exercise files 2019-12-16 11:33:00 -05:00
README.md feat: Add type conversion and parsing exercises 2019-12-16 09:12:13 -05:00
try_from_into.rs I AM NOT DONE comment in conversions exercise files 2019-12-16 11:33:00 -05:00
using_as.rs I AM NOT DONE comment in conversions exercise files 2019-12-16 11:33:00 -05: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.

Book Sections

These are not directly covered in the book, but the standard library has great documentation for conversions here. The FromStr trait is also covered here.