我对 Rust 还很陌生,所以一开始我决定用一些随机生成的元素编写一个老式的 ASCII 文本冒险游戏。但是,我还希望随机生成是基于种子的,这样具有给定种子的地图生成是相同的,以便可以共享。然而,当添加一个用户输入部分来检查用户是否想要手动输入种子或生成随机种子时,我用来存储种子的变量超出了范围,尽管只存在于一个函数中。
我不太确定 rust 变量作用域是如何工作的,特别是因为这一切都在一个函数内,我可能错过了一条未声明种子但我找不到的执行路径。
代码如下:
use std::io::{stdin, stdout, Write};
fn main() { // Get a seed for a random number generator
if input("Initiate with a set seed (y/n)? ").to_lowercase().starts_with('y') {
loop {
let input: String = input("Enter positive integer seed or \"Cancel\" to generate a seed: "); // Gets user seed
if input.to_lowercase() == "cancel" {
let seed: u64 = 824; // Generate random seed here
break;
}
match input.parse::<u64>() {
Ok(value) => {let seed: u64 = value; break;}, // Saves input seed
Err(_e) => {println!("Please enter a positive integer or \"Cancel\" to generate a seed."); continue;} // Retries
}
}
}else{
let seed: u64 = 824; // Generate random seed here
}
println!("Running with seed: {}", seed); // seed is out of scope here
}
fn input(message: &str) -> String {
print!("{}", message); // Prints specified message without newline
stdout().flush().expect("StdOut flushing error in input()"); // Flush stdout to print immediately
let mut input_buffer: String = String::new(); // Declare buffer
stdin().read_line(&mut input_buffer).expect("Input read error in input()"); // Write to buffer
return input_buffer; // Return input
}
let
创建一个新变量,该变量最多存在到下一个右大括号为止。您只想在循环外创建它一次(使用 let mut
,因为您希望能够在循环中更改它):
use std::io::{stdin, stdout, Write};
fn main() {
// Get a seed for a random number generator
let mut seed = 824; // Generate default random seed value
if input("Initiate with a set seed (y/n)? ")
.to_lowercase()
.starts_with('y')
{
loop {
let input: String =
input("Enter positive integer seed or \"Cancel\" to generate a seed: "); // Gets user seed
if input.to_lowercase() == "cancel" {
// Use the already generated seed
break;
}
match input.parse::<u64>() {
Ok(value) => {
seed = value;
break;
} // Saves input seed
Err(_e) => {
println!("Please enter a positive integer or \"Cancel\" to generate a seed.");
continue;
} // Retries
}
}
}
println!("Running with seed: {}", seed); // seed is out of scope here
}
fn input(message: &str) -> String {
print!("{}", message); // Prints specified message without newline
stdout().flush().expect("StdOut flushing error in input()"); // Flush stdout to print immediately
let mut input_buffer: String = String::new(); // Declare buffer
stdin()
.read_line(&mut input_buffer)
.expect("Input read error in input()"); // Write to buffer
return input_buffer; // Return input
}