Rafaelo
Rafaelo

Reputation: 153

Shouldn't R: AsRef<[T]> should work for T=u64?

On the following:

pub fn a<
        T: Copy,
        R: AsRef<[T]> 
    >(
        a_fn: &dyn Fn(&[R], &mut [u64]),
    ) 
{
    let mut result = vec![0, 3];
    b(&[1,2,3], result.as_mut_slice());
}
    
    
fn b<T: Copy, R: AsRef<[T]>>(_: &[R], _: &mut [u64]) {
    unimplemented!();
}
    
fn c() {
    a::<u64, &[u64]>(&b);
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=43d054772b15fa575cc75e87b4eb34d9

I'm trying to be generic on the type R, but eventually use a slice of u64. However, it looks like that [integer] does not implement AsRef<[T]>.

Error:

   Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `{integer}: AsRef<[_]>` is not satisfied
  --> src/lib.rs:9:5
   |
9  |     b(&[1,2,3], result.as_mut_slice());
   |     ^ the trait `AsRef<[_]>` is not implemented for `{integer}`
   |
   = help: the following implementations were found:
             <&T as AsRef<U>>
             <&mut T as AsRef<U>>
             <Arc<T> as AsRef<T>>
             <Box<T, A> as AsRef<T>>
           and 38 others
note: required by a bound in `b`
  --> src/lib.rs:13:18
   |
13 | fn b<T: Copy, R: AsRef<[T]>>(_: &[R], _: &mut [u64]) {
   |                  ^^^^^^^^^^ required by this bound in `b`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error

Upvotes: 1

Views: 144

Answers (1)

John Kugelman
John Kugelman

Reputation: 361849

Change b to take R or &R rather than &[R]. &[R] == &[AsRef<[T]>] has nested slices which I take it is not your intention.

fn main() {
    let mut result = vec![0, 3];
    b(&[1,2,3], result.as_mut_slice());
}
    
fn b<T: Copy, R: AsRef<[T]>>(_: R, _: &mut [u64]) {
    unimplemented!();
}

Playground

Upvotes: 3

Related Questions