Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

as considered harmful #53

Open
wizzwizz4 opened this issue Aug 2, 2020 · 1 comment
Open

as considered harmful #53

wizzwizz4 opened this issue Aug 2, 2020 · 1 comment

Comments

@wizzwizz4
Copy link

Using the as keyword is considered harmful; it silently panics when value are out of range, and it's not explicit about it. Consider replacing:

fn main() {
    let my_number = 100;
    println!("{}", my_number as u8 as char);
}

with:

use std::convert::TryFrom;

fn main() {
    let my_number = 100;
    println!("{}", u8.try_from(my_number).unwrap() as char);
}

Since this a tutorial, I think it would be better to write:

fn main() {
    let my_number = 100 as u8;
    println!("{}", my_number as char);
}

or:

fn main() {
    let my_number: u8 = 100;
    println!("{}", my_number as char);
}

or:

fn main() {
    let my_number = 100u8;
    println!("{}", my_number as char);
}

which are all equivalent, but mean something slightly different to the original code, so you'd need to adjust the text slightly.

(None of these solutions feel good enough for inclusion. Maybe you could take a brief tangent to point out the problem with using as? But panicking hasn't been introduced yet…)

@Dhghomon
Copy link
Owner

Dhghomon commented Aug 2, 2020

Hi @wizzwizz4 - I've actually had it in the back of my mind to simplify the examples here to just do u8 as char since 1) the point of the examples is to just show why there are different numeric types, and 2) (something) as (something) as (something else) is probably a bit much.

So it'll probably end up with just a u8 as char example here, then move casting to a few sections down with some more advanced examples and discussion. TryFrom could work there (I've forgotten to write about it so far) and I could maybe leverage it into starting to talk about traits before the part about actually implementing them, so still in the relatively simple section but not in the super introductory part on top.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants