Hello, I’m fairly new to Rust and came across this. Can someone explain to me how the following example is able to infer the constant value from the array length passed in? At this point, inferred type generation for function calls are a bit hand wavy, to me, does anyone know of a resource that breaks down all the different ways they can be used (for instance in this example I hadn’t seen them used for consts) and what their limitations are in Rust? I often run across a ‘this type can not be inferred’ error without really knowing why not and just throw in the type to make it go away.

Any other examples people could point me to would be appreciated as well.

Thanks!

#[derive(Debug)]
struct Buffer<T, const LENGTH: usize> {
    buf: [T; LENGTH],
}

impl<T, const LENGTH: usize> From<[T; LENGTH]> for Buffer<T, LENGTH> {
    fn from(buf: [T; LENGTH]) -> Self {
        Buffer { buf }
    }
}

fn main() {
    let buf = Buffer::from([0, 1, 2, 3,5]);
    dbg!(&buf);
}

Edit: for some reason, the code markdown is hiding things inside of the <>'s (at least on my lemmy viewing client)

  • deadcream@sopuli.xyz
    link
    fedilink
    arrow-up
    0
    ·
    edit-2
    2 months ago

    It works because the size of an array in main() function is known at compile time. Arrays in Rust have fixed size, at that size is part of their type. The type of the array you pass to from() is [i32; 5]

    • catch22@programming.devOP
      link
      fedilink
      English
      arrow-up
      0
      ·
      2 months ago

      Got it, this completely made sense after your explanation and a second look. Also before I saw this example I hadn’t thought about being able to pass arrays and tuples as generic parameters types. Thanks