For some reason (related to this and that), I require to be generic over reference-like types. I have something like this (with some extra bounds that I omit for the sake of simplicity for this example):
trait GenericRef<'a, T: ?Sized + 'a>: Sized + Copy {}
impl<'a, T: ?Sized> GenericRef<'a, T> for &'a T {}
Now I refactored some functions in my code which previously took a &'a T
to take an R: GenericRef<'a, T>
as argument, instead:
fn takes_ref_to_int_slice(_reference: &[i32]) {}
fn takes_generic_ref_to_int_slice<'a, R>(_reference: R)
where
R: GenericRef<'a, [i32]>,
{}
But then I run into trouble regarding unsized coercions:
fn main() {
// This works due to dereference (from `Vec<i32>` to `[i32]`):
takes_ref_to_int_slice(&vec![1, 2, 3]);
// This works due to unsized-coercion (from `[i32; 3]` to `[i32]`):
takes_ref_to_int_slice(&[1, 2, 3]);
// This does NOT work as `&[i32; 3]` does not unsize-coerce to a `GenericRef<'_, [i32]>`
takes_generic_ref_to_int_slice(&[1, 2, 3]);
// I have to do this:
takes_generic_ref_to_int_slice(&*vec![1, 2, 3]);
// Or better this:
takes_generic_ref_to_int_slice(&[1, 2, 3] as &[_]);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `&[{integer}; 3]: GenericRef<'_, [i32]>` is not satisfied
--> src/main.rs:17:36
|
17 | takes_generic_ref_to_int_slice(&[1, 2, 3]);
| ------------------------------ ^^^^^^^^^^ the trait `GenericRef<'_, [i32]>` is not implemented for `&[{integer}; 3]`
| |
| required by a bound introduced by this call
|
note: required by a bound in `takes_generic_ref_to_int_slice`
--> src/main.rs:7:8
|
5 | fn takes_generic_ref_to_int_slice<'a, R>(_reference: R)
| ------------------------------ required by a bound in this
6 | where
7 | R: GenericRef<'a, [i32]>,
| ^^^^^^^^^^^^^^^^^^^^^ required by this bound in `takes_generic_ref_to_int_slice`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error
I tried to look into std::marker::Unsize
and std::ops::CoerceUnsized
in nightly Rust, but I'm not sure if these traits can help me. I feel like I would run into overlapping implementations.
Can anyone help me with making takes_generic_ref_to_int_slice(&[1, 2, 3]);
work?