rustscope

Variable set in if/else blocks says "not found in this scope" when printed afterward


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);

New to rust, I've been working on this problem for a few, and I must be missing something in the doc. The problem is that code_set isn't being set to anything. I get this error:

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

I added this code before the if/else

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

And "this is not alphabet" prints after the if/else.

What am I missing? I tried taking the last ; out from the if statement, but just got a different set of errors.


Solution

  • Your issue is with Rust Variable Scoping. Variables declared inside a block (like inside an if or else) are scoped only to that block. The variable code_set declared inside the if and else blocks is not accessible outside of those blocks.

    You need to declare code_set outside of the if/else block, and then assign a value to it within the block.

    fn gronsfeld_cipher(data: &str, keys: &[i32], space: char, decode: bool) -> String {
    
    let alphabet = String::from("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    let data = data.to_uppercase();
    
    // Declare code_set outside of the if/else
    let mut code_set: String;
    
    if decode {
        code_set = alphabet.clone().chars().rev().collect();
        println!("if codeset from revs: {}", code_set);
    } else {
        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);
    
    // Rest of the code goes here
    

    }