Closed
Description
I tried this code:
fn main() {
use std::convert::TryFrom;
let s: &[i32] = &[1, 2, 3, 4, 5];
let _: [i32; 5] = TryFrom::try_from(s).unwrap();
let s: &mut [i32] = &mut [1, 2, 3, 4, 5];
let _: [i32; 5] = TryFrom::try_from(s).unwrap();
}
I expected to see this happen: The source is compiled without any error.
Instead, this happened: Compile error as follows.
error[E0277]: the trait bound `[i32; 5]: From<&mut [i32]>` is not satisfied
--> foo.rs:8:23
|
8 | let _: [i32; 5] = TryFrom::try_from(s).unwrap();
| ^^^^^^^^^^^^^^^^^ the trait `From<&mut [i32]>` is not implemented for `[i32; 5]`
|
= note: required because of the requirements on the impl of `Into<[i32; 5]>` for `&mut [i32]`
= note: required because of the requirements on the impl of `TryFrom<&mut [i32]>` for `[i32; 5]`
note: required by `try_from`
--> /Users/rhysd/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/convert/mod.rs:477:5
|
477 | fn try_from(value: T) -> Result<Self, Self::Error>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0277]: the trait bound `[i32; 5]: From<&mut [i32]>` is not satisfied
--> foo.rs:8:23
|
8 | let _: [i32; 5] = TryFrom::try_from(s).unwrap();
| ^^^^^^^^^^^^^^^^^^^^ the trait `From<&mut [i32]>` is not implemented for `[i32; 5]`
|
= note: required because of the requirements on the impl of `Into<[i32; 5]>` for `&mut [i32]`
= note: required because of the requirements on the impl of `TryFrom<&mut [i32]>` for `[i32; 5]`
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0277`.
Is there any reason TryFrom<&mut '_ [T]> for [T; N]
is not implemented though TryFrom<&'_ [T]> for [T; N]
is implemented?
Since the implementation is lack, I needed to convert the mutable slice into immutable slice like below.
let s: &mut [T] = ...;
let a: [T; N] = (&*s).try_into().unwrap();
Meta
rustc --version --verbose
:
rustc 1.56.1 (59eed8a2a 2021-11-01)
binary: rustc
commit-hash: 59eed8a2aac0230a8b53e89d4e99d55912ba6b35
commit-date: 2021-11-01
host: x86_64-apple-darwin
release: 1.56.1
LLVM version: 13.0.0