1

I have the following code so far:

const WORD_SIZE: usize = std::mem::size_of::<usize>() * 8;

pub struct Matrix<const M: usize, const N: usize> {
    pub rows: [[usize; N]; M]
}

impl<const M: usize, const N: usize> Matrix<M, N> {
    const N_words: usize = N * WORD_SIZE;
}

pub fn foo<const M: usize, const N: usize>(mat: &mut Matrix<{M}, {N}>) {
    const a: usize = Matrix<M,N>::N_words;
}

I understand the line Matrix<M,N>::N_words is incorrect. What is the correct syntax?

Edit: I changed my question after someone pointed out to use associated constants as seen here: https://doc.rust-lang.org/reference/items/generics.html#const-generics

user2154420
  • 442
  • 4
  • 17
  • The correct syntax is `Matrix::<{M}, {N}>::N_words`, but currently Rust does not seem to support const generics from outer functions. [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1d90d2c197a682adcb2a2f4bb54d6183) – Sprite May 10 '22 at 18:12
  • Oh bummer. Do you know if there is a feature I could enable to do this? This really seems like something useful. – user2154420 May 10 '22 at 18:16
  • Unfortunately, probably not. Related issues [#57775](https://github.com/rust-lang/rust/issues/57775) [#79955](https://github.com/rust-lang/rust/issues/79955). – Sprite May 10 '22 at 18:23
  • @user2154420 you can make this work by using `let` instead of `const` there. i.e. `let a = Matrix::<{M}, {N}>::N_words;` here's a playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=874f811a31509b928770743c273345ce – mental May 12 '22 at 00:34

0 Answers0