As a beginner in Rust i am trying to practice Rust with some little programs so here is my implementation of Decimal to Binary.
use std::io;
pub fn run() {
let number = input("Enter an input");
println!("{}", to_binary(number));
}
fn input(msg: &str) -> i32 {
println!("{}", msg);
let mut number = String::new();
io::stdin()
.read_line(&mut number)
.expect("Failed to read input");
match number.trim().parse() {
Ok(num) => num,
Err(_e) => panic!("Not a number"),
}
}
fn to_binary(mut decimal: i32) -> i32 {
if decimal == 0 {
decimal
} else {
let mut bits = String::new();
while decimal > 0 {
if decimal % 2 == 0 {
bits.push_str("0");
} else {
bits.push_str("1");
}
decimal /= 2;
}
// reverse the bits
match bits.chars().rev().collect::<String>().parse() {
Ok(num) => num,
Err(_e) => panic!("Something went wrong"),
}
}
}
so feel free to advice anything you consider. i just have three questions in particular
isn't it better to write
input
as a macro ?how can i write
to_binary
as pure function ?wouldn't be better to return binary type from
to_binary
instead i32
-
\$\begingroup\$ Just to make sure: when you say you're a "beginner in Rust", are you also a beginner in general programming, or do you have previous programming experience? \$\endgroup\$Zeta– Zeta2019年01月06日 09:16:56 +00:00Commented Jan 6, 2019 at 9:16
-
\$\begingroup\$ i have a little experience in general programing \$\endgroup\$MAK– MAK2019年01月06日 09:38:23 +00:00Commented Jan 6, 2019 at 9:38
1 Answer 1
isn't it better to write input as a macro ?
No. At best it might work as a generic function.
how can i write to_binary as pure function ?
It already is a pure function, it doesn't mutate or depend on external state
wouldn't be better to return binary type from to_binary instead i32
You should return a String
. Converting to i32 is pretty weird. The numbers inside i32 are already in binary. The point of a to_binary function is pretty much always because you for some reason want a textual representation in binary.
As a quick side note, Rust already has the ability to convert values to binary:
format!("{:b}", value);
Your to_binary function would be a bit simpler if build a Vec or Vec and then converted that instead of building a String.