Follow

Contains advent of code day 1 solution 

Day 1 solved, that was interesting. Took a lot longer than I thought it would due to being a newbie

Code here:

github.com/tom-arto/rust-day1-

Is there anyone who has experience with who could give me some tips to clean up my code to be more idiomatic?

· · Web · 1 · 0 · 0

Contains advent of code day 1 solution 

@natemara maybe you can help if you have a mo? :)

Contains advent of code day 1 solution 

@tom_arto Sure thing!

The reason you were having trouble with `?`, is that you can only use that from inside a function where the return type implements the `Try` trait. For most purposes, this means `Option<T>`, and `Result<T, E>`. If you wanted to use `?` in your `read_input` function, you'd have to return `Result<Vec<String>, std::io::Error>`. Then you could use `?` on any `Result<T, std::io::Error>`

Contains advent of code day 1 solution 

@tom_arto And you were getting the error with `()`, probably because you tried to use it in your main function. The empty type in Rust is written as `()`, and any function with an unspecified return type automatically returns `()`. That's why the compiler said it was expecting a `Result<T, E>`, but found a `()`.

Contains advent of code day 1 solution 

@natemara Thanks for the explanations!

I was getting that when trying to use `File::open(..)?` which was confusing, I thought it was because of open was returning io::Result instead of a proper Result. It threw me for a bit of a loop.

Contains advent of code day 1 solution 

@tom_arto
It's just a type alias, io::Result<T> is exactly the same as Result<T, io::Error>

Contains advent of code day 1 solution 

@tom_arto
Many library authors will make type aliases for Result, just to make their functions more consistent. It's very easy:

`type Result<T> = std::result::Result<T, MyErrorType>;`

Here's a playground demonstrating: play.rust-lang.org/?version=st

@tom_arto Also, not sure how excited you are about the prospect of writing the exact same file IO code every day, but I found a library/toolset designed for making AOC easier for rust users - github.com/gobanos/cargo-aoc

@natemara thanks Nate, may give this a go! And thanks for the tip on type aliases too. Just about to see what day 2 has in store, may read a bit more of Rust in action too

Sign in to participate in the conversation
Mastodon for Tech Folks

This Mastodon instance is for people interested in technology. Discussions aren't limited to technology, because tech folks shouldn't be limited to technology either!