0
votes

How do you pass a const or static to a function in Rust?

Why do these not work?:

const COUNT: i32 = 5;

fn main() {
let repeated = "*".repeat(COUNT);
println!("Repeated Value: {}", repeated);
}

And

static COUNT: i32 = 5;

fn main() {
    let repeated = "*".repeat(COUNT);
    println!("Repeated Value: {}", repeated);
}

They return:

mismatched types
expected `usize`, found `i32`

But these work fine?:

fn main() {
    let repeated = "*".repeat(5);
    println!("Repeated Value: {}", repeated);
}

And

fn main() {
    let count = 5;
    let repeated = "*".repeat(count);
    println!("Repeated Value: {}", repeated);
}

Surely const works the same way as 5? Both should be type i32

= "*".repeat(COUNT)

vs

= "*".repeat(5)

And similarly shouldn't 'static' work like 'let'? What am I missing here? How do you use a const as a parameter to a function call?

1
You would get the same error if you specified the type like you do for const or static: let count: i32 = 5;kmdreko
Interesting. So why does .repeat(5) work?toconn

1 Answers

4
votes

It has nothing to do with the definition of COUNT. repeat takes a usize, not a u32.

You either need to define COUNT as a usize

const COUNT: usize = 5;

Or convert COUNT to a usize when you call repeat

let repeated = "*".repeat(COUNT as usize);