Missing `Option<&[T]>: From<&[T; N]>`

I'm just wondering why this trait impl is not provided in the core lib Option<&'a [T]>: From<&'a [T; N]>? Is this just because there has not been such a need so far?

Something similar was recently merged (impl `From<&[T; N]>` for `Cow<[T]>` by tguichaoua · Pull Request #113489 · rust-lang/rust · GitHub)

Why the Option? Wouldn’t it always be Some?

2 Likes

Well for the function below,

fn foo<'a>(a: impl Into<Option<&'a [i32]>>) { }

The following line will not compile because &[i32;3] doesn't impl Into<Option<&[i32]>>

foo(&[1,2,3]);

You would have to do

foo(&[1,2,3][..]);

Or Some(&[1,2,3])…ah, no, there’s not quite enough inference for that, is there. Point taken!

Yeah

Some(&[1,2,3])

This is going to complain that the trait bound Option<&[i32]>: From Option<&[i32;3]> is not satisfied

1 Like

I expected some of the desirable impls to be impossible due to coherence rules not being able to prove them disjoint from the From<T> for Option<T> impl, but they all seem to be allowable.

The other question is whether adding the impls would be API breaking, as adding new blanket impls can be, since e.g. implementing From<LocalType> for StdType is permitted. But, as far as I can tell, while &T is fundamental, thus allowing crates to write impl From<&LocalType> for Option<&[LocalType]>, [T; N] isn't considered fundamental to coherence and thus attempts to write the impl in a crate cause an error, meaning adding the impls to std should be nonbreaking.

TBH, this is a great example of why I'm not fond of spamming the "into trick" on parameters everywhere. If the parameter was just a: Option<&[i32]>, then Some(&[1, 2, 3]) would work fine.

10 Likes

True. I had the expectation that this would make the API more ergonomic but now it seems like this is not necessarily true

1 Like

This actually doesn't work. You would get error[E0614]: type [{integer}; 3] cannot be dereferenced

Yeah I was just trying it out on play.rust-lang.org. Got the same result.

I've opened a simple PR (impl `From<&[T; N]>` for `Option<&[T]>` by minghuaw · Pull Request #125605 · rust-lang/rust · GitHub). Let's see how this goes.

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