rustgotobasic

Migrating from BASIC to Rust, what do I do with On Gosub?


Most BASIC to Rust code is straightforward. However, what do I do with On Gosub? My brief is to use identical code constructs wherever possible.

Here is the BASIC code (reduced to the minimum).

choice = 3
On choice GoSub labela, labelb, labelc
Print "End"
End

labela:
Print "choice a"
Return

labelb:
Print "choice b"
Return

labelc:
Print "choice c"
Return

Here is what I've done in Rust.

fn main() {
    let subroutines: Vec<fn()> = vec![labela, labelb, labelc];
    let choice = 2;
    if let Some(subroutine) = subroutines.get(choice - 1) {
        subroutine();
    } else {
        panic!();
    }
    println!("End");
}

fn labela() {
    println!("choice a");
}

fn labelb() {
    println!("choice b");
}

fn labelc() {
    println!("choice c");
}

The code is clumsy, worse than the original. I also need to address On Goto constructs, preferably in a uniform way. Can you help?


Solution

  • You have translated the On Gosub to rust correctly. Is it idiomatic? Probably not. The more common way in rust would likely be switch / case :

    match choice{
      1=>subroutines[labela],
      2=>subroutines[labelb],
      3=>subroutines[labelc]
      _=>println!("Unknown choice"),
     }
    

    However that has the disadvantage of losing the arbitrary indexing capability. It will become unwieldy with any larger sets of options.