如何将 const 或 static 参数传递给函数?

toc*_*onn 2 rust

如何将 const 或 static 传递给 Rust 中的函数?

为什么这些不起作用?:

const COUNT: i32 = 5;

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

static COUNT: i32 = 5;

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

他们回来了:

mismatched types
expected `usize`, found `i32`
Run Code Online (Sandbox Code Playgroud)

但这些工作正常吗?:

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

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

当然const工作方式与5?两者都应该是 i32 类型

= "*".repeat(COUNT)
Run Code Online (Sandbox Code Playgroud)

= "*".repeat(5)
Run Code Online (Sandbox Code Playgroud)

同样,“static”不应该像“let”一样工作吗?我在这里缺少什么?如何使用 const 作为函数调用的参数?

pig*_*nds 7

与 的定义无关COUNTrepeat需要 a usize,而不是 a u32

您需要将其定义COUNT为 usize

const COUNT: usize = 5;
Run Code Online (Sandbox Code Playgroud)

或者当你打电话时转换COUNT为 ausizerepeat

let repeated = "*".repeat(COUNT as usize);
Run Code Online (Sandbox Code Playgroud)