Skip to content

as considered harmful #53

Open
Open
@wizzwizz4

Description

@wizzwizz4

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…)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions