DEV Community

Sammy Shear
Sammy Shear

Posted on

Thirty Days of Rust: Day Two

Yesterday was just a warmup, but today actually felt easier than yesterday, probably because I didn't really have to convert types like yesterday. Instead, I wanted to play around with the standard input, so I made a little calculator.

Code

//src/main.rs

use evalexpr::*;
use std::io;

fn main() {
    let mut line= String::new();
    println!("Enter your expression: ");
    io::stdin().read_line(&mut line).unwrap();
    print!("{}", &(&line[..]));
    let out = eval(&(&line[..])).unwrap();
    println!(" = {:?}", out);
}
Enter fullscreen mode Exit fullscreen mode

The only other thing I needed was the evalexpr crate, so I installed version 6 in Cargo.toml, and ran the code. It worked. I had done a bunch of troubleshooting to get to this point though.

Troubleshooting

The first crate I tried before evalexpr was just eval, but for whatever reason I couldn't get it working with the same style of code. I probably could've tinkered around a little more but if I'm being honest I didn't understand what the documentation was trying to tell me, and evalexpr worked right away. I'm sure it was just a silly mistake on my part though.
I also had to figure out how to get from a String to a &str, which lead me to stack overflow, finding two questions that gave me this function and this expression (&(&line[..])) to print the type and change the type:

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>());
}
Enter fullscreen mode Exit fullscreen mode

So I used the function for debugging, and the expression to switch the type so eval could actually evaluate it. It's worth mentioning that I'm not sure that part was necessary with the new crate because I did this in an attempt to fix the problem I had with the old crate.

Conclusion

Again, I'm enjoying myself so far. This is a cool language that I understand why so many people love. I don't know how much I will integrate Rust into my workflow after this challenge, but I'm guessing it'll make its way in given what the experience has been like so far.

Discussion (1)

Collapse
chayimfriedman2 profile image
Chayim Friedman

You don't need the double ampresand or the [..] (not in this case, at least). A simple &line will do.