Why not impl<'a> From<&'a str> for &'a [u8]?

There is impl From<Box<str>> for Box<[u8]>.

There's also one for Rc<str> and Arc<str>. Definitely feels missing.

Shouldn't all of these be TryFrom? It seems weird to me to have potentially panicking (on invalid UTF-8) From implementations in the first place.

strs are always valid UTF-8 so the conversion is infallible (but not the other way around) and I think TryFrom<[u8]> for str is not implemented because this direction is somewhat ambiguous, since other encodings are possible (instead, there is str::from_utf8)

3 Likes

Oops, read the conversion the other way around.

Actually, I don't see a reason for this impl to exist, since we already have str::as_bytes(), and wherever you would want to use something like Into<&'a [u8]> , it's probably easier to use AsRef<[u8]>, which str does implement. @stackinspector do you have a particular use case in mind?

2 Likes

Recent Zulip discussion: https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/.60std.60.20conversion.20traits.20are.20a.20mess

1 Like

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