Was it a mistake to make `as` for casting too simple to use?

I chipped in the conversation in the narrowing_rem issue on rust-lang/rust, and the original poster has a point in their (currently) last comment:

if you write lot of numerical code in Rust you slowly understand that current "as" casts are unsafe and they lead to problems in C code. In Rust there's try_from to avoid this risk

When I need to do a conversion, I find it a lot simpler (but also potentially wrong) to just throw in as:

let foo = bar as u8;

As opposed to the arguably better in most situations but also more verbose:

use std::convert::TryFrom;

let foo = u8::try_from(bar).expect("bar was larger than expected");

Would you say it was a mistake to make as "so simple" to use, and more easily accessible than TryFrom? (Perhaps it would help if TryFrom was in the prelude, but it would still be more verbose).

Unfortunately, I can't think of any way in which this could be easily solved. Perhaps as should behave like try_from + unwrap, and then there would be another, more verbose method to do what as does, but it all boils down to which would be more common I suppose.

1 Like

I do think the current situation is unfortunate, yes.

You might be interested in this discussion about "as":

1 Like

Oh thanks, my quick search for a topic like that was perhaps a bit too quick :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.