use std::io;
fn main() {
let mut number_buf = String::new();
println!("Enter a number");
let number = read_f32_line(&mut number_buf);
println!("Enter the percentage that you want to be removed from the previous number");
let percentage = read_f32_line(&mut number_buf);
let final_number = number * percentage / 100.0;
println!(
"{}% of {}: \x1b[34;1m \x1b[1m \n{} \x1b[0m",
percentage, number, final_number
);
}
fn read_f32_line(mut buf: &mut String) -> f32 {
buf.clear();
io::stdin().read_line(&mut buf).expect("Failed to read line");
buf.trim().parse().expect("Input was not a valid number")
}
Allocating memory on the heap (done internally by String, Vec, Box, any type that has an internal buffer of data whose size isn't known at compile time) is somewhat expensive compared to allocating memory on the stack, which costs little or nothing. It's more efficient to only allocate a buffer once and reuse it, instead of doing it every time we want to read a number.
Of course, there might still be some allocations if the string needs to grow beyond the capacity it already has allocated, but sharing a buffer over many uses will be much more efficient than creating a new one each time.
Since this program only reads two numbers it's not a big deal, but it's good design to minimize allocations when you can.
It does, but you can't just access them mutably, because it wouldn't be thread-safe. You could lock it in a Mutex, and there a libraries that provide things like thread-local statics, but this was the simplest way to handle it.
this set of personal projects are an ends to mean. building poc. I want to code the right way. but the problem is i just fail to invest the time to do it right. doing it all dirty hurts but I gotta keep my FT job and also take care of baby.
68
u/_deton8 Jun 25 '21
Your programming skills are rusty
11
u/GreekCSharpDeveloper wicked Jun 25 '21
Here's the code: https://paste.rs/ZoT.rs
7
u/Bobbbay Jun 25 '21
Just added the Rust flair, feel free to update your post flair. 🍻
25
u/[deleted] Jun 25 '21
what do you mean it doesn't seem that bad
oh
oh
15
u/NetherFX Jun 25 '21
Oh gawd, hopefully you learned from your mistakes, Rust can be very elegant
12
u/[deleted] Jun 25 '21
I feel like everyone is allowed to write terrible rust when they're starting out in it. It's very specific with its own set of rules.
6
u/TinyBreadBigMouth Jun 25 '21
5
u/[deleted] Jun 25 '21
Ferris is gonna whoop your ass.
3
u/[deleted] Jun 25 '21
You should get the tetanus vaccine. :p
3
u/KaiParekh16 Jun 26 '21
Dude needs to take a break from programming to preserve his sanity
2
u/Jackiboi307 Jun 25 '21
vims standard theme? why
0
u/[deleted] Jun 25 '21
[deleted] — view deleted comment