How to pass "const" as an argument to a function

Hello,

I get the following errors for the "pseudo_rand_seq" function.
I need to pass a const to the function so that I can create an array with it. I am coming from a C background. How do I do this in Rust? Thanks

error: expected pattern, found keyword `const`
      --> src\ts_36211.rs:119:20
       |
119 | fn pseudo_rand_seq(const n_bits: u32, cinit: u32) -> u32 {
       |                 ^^^^^ expected pattern

error[E0425]: cannot find value `n_bits` in this scope
    --> src\ts_36211.rs:128:32
       |
128 |     let c: [u32; n_bits] = [0; n_bits];
       |               ^^^^^^ not found in this scope

Src

// Pseudo random sequences
// TS 36.211 V12.2.0, section 7.2
// Pseudo-random sequences are defined by _a length-31 Gold sequence

fn pseudo_rand_seq(const n_bits: u32, cinit: u32) -> u32 {
    //let i: u32  = 0;
    let mut x1: u32 = 0;
    let mut n1: u32 = 0;
    let mut x2: u32 = 0;
    let mut n2: u32 = 0;

    x1 = x_1();
    x2 = x_2(cinit);
    let c: [u32; n_bits] = [0; n_bits];
    for i in 0..n_bits {
        n1 = ((x1 >> 3) ^ x1) & 0x1;
        n2 = ((x2 >> 3)^(x2 >> 2)^(x2 >> 1)^x2) & 0x1;
        x1 = (x1 >> 1) | (n1 << 30);
        x2 = (x2 >> 1) | (n2 << 30);
        c[i] = n1 ^ n2;
  }
  c
}

Why would you need to pass a constant into a function? Just make it a non-constant function.


This is called const generics (If I'm correct) and is not available in rust as of yet.

Removing the const keyword throws the following error:

error[E0435]: attempt to use a non-constant value in a constant
  --> src\ts_36211.rs:128:18
    |
128 |     let c: [u32; n_bits] = [0; n_bits];
    |                  ^^^^^^ non-constant value

Oh, as I said earlier, this is a const-generic problem, which is not (yet) supported in rust. This makes working with sized arrays painful. I'd use a Vec like so:

fn pseudo_rand_seq(n_bits: u32, cinit: u32) -> u32 {
    //...
    let c = vec![0; n_bits];
    //...
}

This uses the vec! macro which expands to a for loop which fills a Vec and returns it. Also, what are you trying to return at the end? You return -> u32 but (hypothetically) return -> [u32; n_bits]


This can also be accomplished with the Vec::<T: Clone>::resize(&mut self, usize, T) method.

2 Likes

const is a value known at compile time. Array sizes must be const so compiler can know its size at compile time, which allows placing them directly on stack memory without any heap allocation. Function parameters are value that selected by caller at runtime, thus it cannot be a const.

When the "const generics" arrives, you can pass a const as a generic parameters though.

fn pseudo_rand_seq<const n_bits: usize>(cinit: u32) -> [u32; n_bits] {..}

Note that you can construct array at caller side, and pass &mut [u32] as a argument to this fn.

Thanks. I want the function to return a pointer to u32 or a bit string