#Variable Scope Question

5 messages · Page 1 of 1 (latest)

onyx cobalt
#

I am learning Rust, and created a simple binary search bot for the guessing game the book walks you through. I currently create the number the bot should guess into the function, but technically the bot function shouldn't have access to the secret number variable. I want to initialize it somewhere else, but not have full access to it. In C# I'd normally create my variable at a class level scope. What is the equivalent in Rust? NB: The closest language I've ever used to Rust is Golang for work. I have an OOP background. I was Googling around and it looks like what I want in Rust would be like making a bot manager which calls a function that has a callback to the manager of when it guesses which checks it against the secret number there?

Code: https://blazebin.io/basic/viewer/uupzvevcbzcv/0

sand gust
#

What I would suggest is to define a separate type for the bot:

struct Bot {
    min_num: u32,
    max_num: u32,
}

impl Bot {
    fn current_guess(&self) -> u32 { ... }

    fn your_guess_was(&mut self, correct: bool) { ... }
}

Then the Bot code does not have access to any of the game state except itself.

#

(Note that this is just encapsulation for when the rules of the language are being followed, not security — the bot could use unsafe code to peek into what the rest of the program is doing.)

#

Note that it's not critical that there is a declared type, actually, but just that there are functions. The type is a convenience for passing data to the functions.

#

@onyx cobalt