Why I cannot convert slice to reference to trait?

⚓ Rust    📅 2025-09-11    👤 surdeus    👁️ 10      

surdeus

Warning

This post was published 63 days ago. The information described in this article may have changed.

For code below rustc reports:

|     let foo: &dyn Foo = slice;
|                                    ^^^^^ doesn't have a size known at compile-time

but size of slice is obviously known (pointer + length), so what is real problem with my code?

use std::any::Any;

trait Foo {
    fn len(&self) -> usize;
    fn get(&self, index: usize) -> Option<&dyn Any>;
}

impl<T> Foo for [T]
where
    T: 'static,
{
    fn len(&self) -> usize {
        self.len()
    }

    fn get(&self, index: usize) -> Option<&dyn Any> {
        <[T]>::get(self, index).map(|v| v as &dyn Any)
    }
}

fn main() {
    let v = Vec::<i32>::new();
    let slice = v.as_slice();
    let foo: &dyn Foo = slice;
}

2 posts - 2 participants

Read full topic

🏷️ Rust_feed