DEV Community

Cover image for Rust: Keeping You Guessing
Jeff Mitchell
Jeff Mitchell

Posted on

Rust: Keeping You Guessing

If you've been following my writings at all, you'll notice a lot of what I think of as beginner oriented content about the Rust programming language. It's my attempt to put my understanding of the topic at hand into words and ideas that I can go back to later. It may not always be complete or provide the best picture, but it supplements learning I do elsewhere.

They say after all the best way to understand something is to try to explain it to someone else. I actually wrote all of what I've posted to date about two years ago. I'm bringing it over to a platform where potentially I can reach more people. Let's face it, in 2022 the free internet was dead...in 2025 it's even worse. If you're not on some kind of curated platform you're basically knowhere.

In this vein, I'm doubling down a bit on basics. I started reading The Rust Book, probably two years ago, but never finished. I find it a little...obtuse. They don't write with very many concrete examples that are representitive of what you'd see in real life, as such I have a hard time learning from it. I'm the type of learner that needs to do. Abstract concepts don't mean much to me until I actively try and make something real.

The unfortunate side effect of this is a tendency to gloss over the basics, as I don't find them interesting (understandable?) on their own. I seek out some thing or some project, usually way too big for me, and try to run before I walk. Over time, and with lots of repetition, things sink in.

I kind of consider it a bit of a learning disability, and I know I'm probably too harsh on myself. I wish amongst all the wishes that I could learn to slow down and take joy in understanding all the basic bits.

I don't see myself changing anytime soon. It's best to just go with it and not fight.

Anyhow, enough navel gazing. I said a moment ago that I'd returned in 2025 to The Rust Book. Yesterday I finished Chapter 2, which is where the authors walk you through creation of a Guessing Game.

Today I challenged myself to do it from memory.

Did it, mostly, with some fumbling. Here is the super overengineered version:

// src/main.rs

// Guessing Game project from Chapter 2 of "The Rust Book"

// dependencies
use color_eyre::Result;
use rand::{thread_rng, Rng};
use std::cmp::Ordering;
use std::io::{stdin, stdout, Write};

// function which writes an output message
fn write_msg(msg: &str) -> Result<()> {
    stdout().write_all(msg.as_bytes())?;
    Ok(())
}

// main function
fn main() -> Result<()> {
    // initialize color_eyre
    color_eyre::install()?;

    // initialize with a random number that the user will guess
    let mut rng = thread_rng();
    let number = rng.gen_range(1..=100);

    // game event loop
    loop {
        // user input
        let msg = "Please enter a number between 1 and 100...\n";
        write_msg(msg)?;
        let mut guess = String::new();
        stdin().read_line(&mut guess)?;
        let msg = format!("You guessed: {}", guess);
        write_msg(msg.as_str())?;

        // compare the user's input with the random numb;
        let guess: i32 = guess.trim().parse()?;

        match guess.cmp(&number) {
            Ordering::Less => {
                let msg = "Too small!\n";
                write_msg(msg)?;
            }
            Ordering::Greater => {
                let msg = "Too big!\n";
                write_msg(msg)?;
            }
            Ordering::Equal => {
                let msg = "You got it! You win\n";
                write_msg(msg)?;
                break;
            }
        }
    }

    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

Things you'll notice which are way beyond what's introduced in Chapter 2:

  • use of the color_eyre crate for error handling. This crate enables use of the ? operator which simplifies error handling for you and reduces the amount of boilerplate you're resposible for.
  • no macros...for some reason I'm on a no macros kick, as I want to understand what's going on underneath. You'll see a write_msg() function, which accepts a string slice and calls the stdout() function to create a handle to stdout, giving us something that implements the Write trait so that we can write a message to the console.

Other than that, it's pretty much the same as from Chapter 2. I'd thought briefly about turning this thing into some kind of API, but in the end just kept it to the some direction as in the book.

This is a very trivial program, but it highlights a lot of important concepts in Rust and is a great jumping off point for your own exploration. I share here because I want to put my work out there, perhaps get some constructive feedback, and perhaps help others in their own Rust journeying.

Good night and thanks for reading!

References:

Top comments (9)

Collapse
 
speeddymon profile image
Speeddymon

This popped up in my Google feed in my phone. Such a great read for me despite not knowing a lick of Rust, because your learning method is the same as mine. I learn the absolute minimum of the basics; enough to write hello world and then go find projects I can contribute to and start asking lots of questions. I'm a cloud architect so I mostly deal with terraform and the CNCF ecosystem so vastly different coding between us but...

I'm also hard on myself for it like you. So! I'm dedicating my new year's resolution to your post. I'm going to work on not being hard on myself for it at first. I've made a great career with what I've learned.

I'm also not changing completely by "slowing down" but I think eventually I'll work up to working on also trying to maybe just tap the brakes... briefly.

I invite you to do the same! Cheers!

Collapse
 
crusty-rustacean profile image
Jeff Mitchell

Yeah, let's be honest, you're right. This is a brake tap for me. I know myself and I'm already itching to back to "my way" :) Thanks for commenting! It's nice to know there's at least one kindred spirit out there.

Collapse
 
armel_peel_b039d28c8c04ce profile image
Armel Peel

I keep trying to tell newcomers Rust is not the future. But Rust, like Python and Javascript, is an internet horse. The internet is going to cheat to make sure their horse always wins. They are going to portray their horse as the best in the race. They are going to erase anything speaking negatively about their horse. And last but not least, when their horse falls over dead, they are going to show old pictures of the horse and say it is still alive.

The internet listens to advertising fads and no longer listens to real programmers. I have taught many programming courses and frankly this is a task you should be able to complete in any language in maybe 10 lines of code or less. You have used many more than 10 lines of code. You have included 4(!!!) external libraries for a problem so simple, and you wrote a one line wrapper around a print function.

I strongly doubt you could program in any language effectively. And Rust "memory safety" looks to be completely over your head, as from your code it looks like you will never properly grasp the concept of pointers and what memory even is or how it works. A lot of broken redundant code does not a real program make. You have made more than a few beginners mistakes which I just stopped counting and chalked up to "you cant really program." Your guessing game in Perl. Golfed at 114 characters.

perl -le '$n=int(rand(100));do{print"Guess($n):";chomp($g=<STDIN>);$g<$n?print"low":print"high"}while($n!=$g);print"correct!"'

Steve Ballmer used this type of problem to screen candidates at Microsoft, except the real problem was using a binary search to find his number in log(n) time.

youtu.be/svCYbkS0Sjk

It looks like you just couldnt figure that part out, and you just infinitely guess randomly until you happen upon the correct answer. I worked out the correct solution here. Solution in log(n) time.

old.reddit.com/r/perl/comments/1ge...

Beginners: Go to school, learn C, stay away from shady shortcuts. It is not the new fad you need, it is the know how and ability you lack. Even if you write hello world in 10 different languages, you still have a less than beginners grasp of 10 languages. Learn one language WELL, preferrably C, the real programmers are here. If you cant learn C, programming is probably not for you. Try to find a skill or major that suits your strengths better. It takes 4, YES FOUR FULL years to CONSIDER becoming a competent programmer. Dont believe the learn in a couple month scams.

And also, stay out of the casinos.

Collapse
 
joshua_whitney_b3891822a5 profile image
Joshua Whitney

This is a bad take. Yes, this code could be simplified. Yes, even in Rust. Yes, your code is only 4 lines long. I personally find the Rust code easier to follow. Rust is not a bad language by any means. It's adoption by virtually all FAANG companies is a testament to this. These are companies that have created their own languages in some instances, and have still found use cases where Rust has been the best ROI. Also, your elitist put down of this code helps nobody. If you are going to critique it, be specific. Saying you doubt this person's ability in all languages, based on a trivial program in a language they are currently learning, is ridiculous.

Collapse
 
crusty-rustacean profile image
Jeff Mitchell

The commenter has a point, which was delivered in an unnecessarily mean spirited manner (that’s what you get, for putting yourself out there) but I’m going to set that aside, learn from it, and make adjustments to my approach.

Collapse
 
armel_peel_b039d28c8c04ce profile image
Armel Peel

I've taught enough classes, had enough students, graded enough tests, quizzes, and projects, where I can look at this code and see first semester student at best. I was specific in my critique. The one line wrapper function around the print function is an obvious one. The 4 external libraries are another.

The fact that you very intentionally didnt use any if statements where they are definitely best practice is very telling. The fact that you didnt use any mathematic operators and instead used methods says a person that is probably not very comfortable with math. At university CS students do nearly as much math as Math majors, despite the internet myth that math is not required.

Your code doesnt read very well for a problem so simple. My golf code was intentionally short but standard code would read the same is the equivalent C/C++ code. Your code isnt "familiar" for such a simple problem. My first question would be why have you chosen to write it this way instead of the standard if guess > n then... code.

My non golfed code is similar to the way most first year students would write it. Your code, though it does appear to work, looks like you went off the rails somewhere. You did something kind of weird and got the right answer. And that kind of thing wears off quickly. That would be a more specific critique.

By the way you did not use if statements, and you did not use any math operators in a problem where they would be the most straightforward and correct solution usually means you dont know how to use them. And because of this, it seems unlikely you would be able to master extremely difficult subjects like pointers and memory management. Or use another language well. I would also question your knowledge of math and conditionals.

If you know other languages, you wouldnt have written your code like this likely. Here is my non golfed Perl code. Which should be miles easier to read. Your code looks like you ran really far in the wrong direction which would be my opinion. It is correct to draw these conclusions because the problem is so easy and straightforward. Early lessons from a beginners course. Like... What were you thinking?

#!/usr/bin/perl -w
my ($n,$g) = (int(rand(100)),undef);
do{
print "Enter a guess ($n): ";
chomp($g = <STDIN>); #remove the newline
$g < $n ? print "$g Missed low\n" : print "$g Missed high\n";
}while($n != $g);
print "Guessed correctly!\n";

Thread Thread
 
pfernandom profile image
Pedro F Marquez • Edited

The code in the post has things to improve, but the idea that just because it doesn't use if statements and math operators OP doesn't know how to use them is flawed and extremely biased.

We use "if guess < n ... then" in other languages because there is no other idiomatic way to do so. In Rust, there is: The Ordering enum is idiomatic, clear in intent and leaves no room for mistakes (with boolean operators and if statements you can easily miss a case, while Rust's compiler will force you to handle each case of the enum).

Also, 4 external dependencies? Where did you get that from? It's only two, and rand is fully required because the std doesn't include pseudo-random number generation (color-eyrie is fully unnecessary, and the whole code could be simplified without it and the whole use of the ? operator, though).

To me, it sounds like you are the one that is not familiar with Rust, not OP, and you dislike it so much that you will take anything you don't like about ithr language and point it out as a rookie mistake.

Rust is by no means perfect, and probably an overkill for the scenario in this post, but in the end its goal is just to demonstrate how to do something simple in this language. If you prefer C, that's cool, stick to it, but don't try to pass your bias and dislike for a language as an objective critique of the quality of a code snippet by someone who openly is admitting is just learning the language.

Thread Thread
 
crusty-rustacean profile image
Jeff Mitchell

Thanks for your support.

It's amusing, I read Chapter 2, then I went off to work my way through to the same end result without looking again. At first, I did use a traditional if conditional statement. Then I remembered, that's not the Rust way.

I think the commenter needs to follow the link at the end of my post, which was the point here, before throwing stones. I'm fine to receive harsh feedback. In fact, that's why I've returned to learning in public like this. However, what's not appreciated is feedback founded in ignorance of the actual language concepts I'm working through.

Let's see what happens when I do my next piece about the Result type. Will probably get the comment that I'm not doing it right because I didn't handle exceptions! :)

Collapse
 
crusty-rustacean profile image
Jeff Mitchell • Edited

Thanks for your pointed feedback. Everyone has the right to learn and improve.