Why does try_into, but not into, work for arrays?

Ref: Rust Playground

into and try_into are usually both provided if either is provided. But not here.

No, that's simply not true. What would be the point of having two separate traits then, if they did exactly the same thing?

The whole point of TryInto is that it's fallible, i.e., it represents a conversion that may or may not be possible. Into represents a conversion that's always possible. Thus, TryInto can't possibly imply Into.

Converting a Vec to a fixed-size array may fail if the size of the Vec (which can dynamically change) doesn't happen to match the size of the target array. Therefore, this conversion is fallible, and quite obviously, Into (or From) shouldn't be implemented in this direction.


Ah. Per From in std::convert - Rust that's correct. " Note: This trait must not fail." I had thought that From and Into were allowed to panic. But they're not.

You may be used to both being available because

But it's a one-way street.

You can't rely on From implementations not panicking for soundness (since it's safe to write such an implementation), but you'll break people's expectations.


In general, panics should only be used for irrecoverable errors.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.