在 if/else 块中设置的变量在随后打印时显示“在此范围内找不到”

问题描述 投票:0回答:1
fn gronsfeld_cipher(data: &str, keys: &[i32], space: char, decode: bool) -> String {

    let alphabet = String::from("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    let data = data.to_uppercase(); // Convert data to uppercase
    
    if decode {
        let mut code_set: String = alphabet.clone().chars().rev().collect();
        println!("if codeset from revs: {}", code_set);
    } else {
        let mut code_set: String = alphabet.clone();
        println!("if codeset from clone: {}", code_set);
    }

    println!("Code Set = {}, data: {}", code_set, data);

刚接触 Rust,我已经研究这个问题好几年了,我一定在文档中遗漏了一些东西。问题是

code_set
没有被设置为任何值。我收到此错误:

error[E0425]: cannot find value `code_set` in this scope
  --> src/main.rs:16:41
   |
16 |     println!("Code Set = {}, data: {}", code_set, data);
   |                                         ^^^^^^^^ not found in this scope

我在 if/else 之前添加了这段代码

let code_set = String::from("This is not the alphabet");

并且在 if/else 之后打印“这不是字母表”。

我错过了什么?我尝试从 if 语句中取出最后一个

;
,但只是得到了一组不同的错误。

rust scope
1个回答
0
投票

您的问题与 Rust 变量作用域有关。在 Rust 中,块内声明的变量(如 if 或 else 内)的作用域仅限于该块。因此,在 if 和 else 块内声明的变量 code_set 在这些块之外不可访问。

您需要在 if/else 块之外声明 code_set,然后在块内为其赋值。

fn gronsfeld_cipher(data: &str, keys: &[i32], space: char, decode: bool) -> String {

let alphabet = String::from("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
let data = data.to_uppercase(); // Convert data to uppercase

// Declare code_set outside of the if/else
let mut code_set: String;

if decode {
    // Reverse the alphabet for decoding
    code_set = alphabet.clone().chars().rev().collect();
    println!("if codeset from revs: {}", code_set);
} else {
    // Keep the alphabet as is for encoding
    code_set = alphabet.clone();
    println!("if codeset from clone: {}", code_set);
}

// Now code_set is in scope here
println!("Code Set = {}, data: {}", code_set, data);

// Return an empty string for now, to match the return type
String::new()

}

© www.soinside.com 2019 - 2024. All rights reserved.