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
Taylor Yu 2dc93cadda fix(from_str, try_from_into): custom error types
Remove the use of trait objects as errors from `from_str` and
`try_from_into`; they seem to have caused a lot of confusion in
practice. (Also, it's considered best practice to use custom error
types instead of boxed errors in library code.) Instead, use custom
error enums, and update hints accordingly. Hints also provide
some guidance about converting errors, which could be covered
more completely in a future advanced errors section.

Also move from_str to directly after the similar exercise `from_into`,
for the sake of familiarity when solving.
2021-06-24 21:33:41 -05:00
..
as_ref_mut.rs chore: Alter whitespace for consistency 2020-07-11 11:50:54 -07:00
from_into.rs feat(from_into) : add test for checking unnecessary trailing value 2021-01-09 00:08:38 +09:00
from_str.rs fix(from_str, try_from_into): custom error types 2021-06-24 21:33:41 -05:00
README.md docs(exercises): updated all exercises readme files 2021-04-23 19:54:31 +02:00
try_from_into.rs fix(from_str, try_from_into): custom error types 2021-06-24 21:33:41 -05:00
using_as.rs fix(using_as): Add test so that proper type is returned. (#512) 2020-09-07 19:09:27 +02: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.