Converting a 12h clock to 24h clock I started picking up Rust on my free time, and I'm curious about what style errors have I made and where should I improve as a programmer.

The problem is from HackerRank and very simple: there is a fixed-format input of time in 12 hour format (07:05:45PM), and the objective is to convert it to 24 hour format (19:05:45).

My own first impressions:


The problem is very simple, but the code seems too lengthy?
I'm nesting match constructs, and it doesn't seem concise.




use std::io::{stdin, BufRead, Error, ErrorKind, Result};

struct Time {
    hour: u8,
    minute: u8, 
    second: u8
}

impl Time {
    pub fn from_12h(time : String) -&gt; Result&lt;Time&gt; {
        assert!(time.chars().count() == 10);
        let hour : String = time.chars().take(2).collect();  
        let minute : String = time.chars().skip(3).take(2).collect();
        let second : String = time.chars().skip(6).take(2).collect();
        let period : String = time.chars().skip(8).take(2).collect();

        match Time::hour_from_12h_to_24h(hour.parse::&lt;u8&gt;().unwrap(), period) {
            Ok(hour_24h) =&gt;
                Ok(Time {
                    hour: hour_24h,
                    minute: minute.parse::&lt;u8&gt;().unwrap(),
                    second: second.parse::&lt;u8&gt;().unwrap()
                }),
            Err(e) =&gt; Err(e),
        }
    }

    fn hour_from_12h_to_24h(hour : u8, period : String) -&gt; Result&lt;u8&gt; {
        match period.as_ref() {
            "AM" =&gt; Ok(hour % 12),
            "PM" =&gt; Ok(hour % 12 + 12),
            _ =&gt; Err(Error::new(ErrorKind::InvalidData, format!("invalid period {}", period))),
        }
    }

    pub fn to_24h(&amp;self) -&gt; String {
        format!("{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
    }
}

fn main() {
    match read_12h_time() {
        Ok(time_12h) =&gt;
            match Time::from_12h(time_12h) {
                Ok(time) =&gt; println!("{}", time.to_24h()),
                Err(err) =&gt; println!("error: {}", err)
            },
        Err(err) =&gt; println!("input error: {}", err),
    }
}

fn read_12h_time() -&gt; Result&lt;String&gt; {
    let mut buffer = String::new();
    match read_line(&amp;mut buffer) {
        Ok(length) =&gt;
            match length {
                10 =&gt; Ok(buffer),
                _ =&gt; Err(Error::new(ErrorKind::InvalidInput, format!("expected 10 characters, got {}", length)))
            },
        Err(e) =&gt; Err(e),
    }
}

fn read_line(buffer : &amp;mut String) -&gt; Result&lt;usize&gt; {
    let stdin = stdin();
    let mut handle = stdin.lock();
    handle.read_line(buffer)
}
Your code doesn't really work when used by humans. The first thing I did was run the code and type in a time, which failed. When a human enters data through the terminal, they will hit Enter, which is returned from read_line:

$ echo '07:05:45PM' | cargo run
input error: expected 10 characters, got 11
$ echo -n '07:05:45PM' | cargo run
19:05:45

Style issues - learn to love rustfmt:


There's no space before : when specifiying a type on a variable.
Use trailing commas.
Match arms longer than one line should use curly braces {}

Accept a &amp;str instead of String; the function doesn't need to take ownership of the string.
There's no need for the turbofish (::&lt;&gt;) on the parse calls; type inference handles that just fine.
Become very familiar with all the methods on Option and Result and Iterator. These are the bread and butter of idiomatic, concise, and performant Rust code. Specifically, if you match on a Result and have a match arm for Ok and Err, it's likely you want to use Result::map.
Avoid iterating through the characters from the beginning multiple times, it is less efficient than needs to be. Instead, use the same iterator multiple times through Iterator::by_ref.
I'd use expect in your main method, instead of matching and printing. There is a difference between the two, expect will cause a panic on Err, but that seems reasonable in main.
I never use unwrap, instead preferring at least expect; this helps find the line when the code finally fails.
Library code should very rarely panic; they should report errors. Especially report errors when it's because of input supplied to the code, panic for internal logic errors.
The match in read_12h_time can be flattened; you can pattern match against Ok(10) directly.
stdin doesn't need to be explicitly locked; read_line will lock it.




use std::io::{stdin, Error, ErrorKind, Result};

struct Time {
    hour: u8,
    minute: u8,
    second: u8,
}

impl Time {
    pub fn from_12h(time: &amp;str) -&gt; Result&lt;Time&gt; {
        assert!(time.chars().count() == 10);
        let mut chars = time.chars();

        let hour: String = chars.by_ref().take(2).collect();
        let minute: String = chars.by_ref().skip(1).take(2).collect();
        let second: String = chars.by_ref().skip(1).take(2).collect();
        let period: String = chars.by_ref().take(2).collect();

        Time::hour_from_12h_to_24h(hour.parse().unwrap(), &amp;period).map(|hour_24h| {
            Time {
                hour: hour_24h,
                minute: minute.parse().unwrap(),
                second: second.parse().unwrap(),
            }
        })
    }

    fn hour_from_12h_to_24h(hour: u8, period: &amp;str) -&gt; Result&lt;u8&gt; {
        match period {
            "AM" =&gt; Ok(hour % 12),
            "PM" =&gt; Ok(hour % 12 + 12),
            _ =&gt; Err(Error::new(ErrorKind::InvalidData, format!("invalid period {}", period))),
        }
    }

    pub fn to_24h(&amp;self) -&gt; String {
        format!("{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
    }
}

fn main() {
    let time_12h = read_12h_time().expect("input error");
    let time = Time::from_12h(&amp;time_12h).expect("error");

    println!("{}", time.to_24h());
}

fn read_12h_time() -&gt; Result&lt;String&gt; {
    let mut buffer = String::new();
    match read_line(&amp;mut buffer) {
        Ok(10) =&gt; Ok(buffer),
        Ok(length) =&gt; {
            Err(Error::new(ErrorKind::InvalidInput,
                           format!("expected 10 characters, got {}", length)))
        }
        Err(e) =&gt; Err(e),
    }
}

fn read_line(buffer: &amp;mut String) -&gt; Result&lt;usize&gt; {
    stdin().read_line(buffer)
}




On to bigger issues:


I don't like that the AM/PM matching and hour conversion are tangled together.


Instead, introduce an enumeration to handle the AM/PM.

It feels like 12 hour time is a different type from 24 time.


Rename existing type to something unique.
Store the new AM/PM enumeration.
Introduce new type and add conversion methods.

I don't like reusing io::Error for your own errors.


Introduce a custom error type. I like to use quick_error, but there are other solutions.

I don't like that IO is embedded inside of the logic of the library.


Separate IO and parsing logic and only combine them at a higher level - in this case main.
Push time-specific logic (e.g. 10 character checks) back into the library. Note that this removes the duplication of the logic in the assert and removes a panic inside the library.

The code doesn't fully participate in the Rust ecosystem.


Implement traits like FromStr and From and Display (perf!).
Derive standard traits to make it easier to use your types: #[derive(Debug, Copy, Clone, PartialEq)] is a good set.

There are too many panics inside the library portion.


Fully utilize Result and try! or the try operator ?.

There's too much unneeded allocation.


Instead of using characters and collecting them back to strings, operate on the incoming string and take slices instead.
Formatting can write directly into a formatter; there's no reason to allocate a string to just turn around and print it.





#[macro_use]
extern crate quick_error;

use std::str::FromStr;
use std::io::stdin;
use std::fmt;

quick_error! {
    #[derive(Debug, Clone, PartialEq)]
    enum Error {
        MissingMeridian {
            description("missing the meridian")
            display("Missing the meridian")
        }
        InvalidMeridian(what: String) {
            description("invalid meridian")
            display("Invalid meridian: {}", what)
        }
        MissingComponent(which: TimeComponent) {
            description("missing a time component")
            display("Missing {}", which)
        }
        InvalidComponent(which: TimeComponent, why: std::num::ParseIntError) {
            description("invalid time component")
            display("Invalid {}: {}", which, why)
            cause(why)
        }
    }
}

type Result&lt;T&gt; = std::result::Result&lt;T, Error&gt;;

#[derive(Debug, Copy, Clone, PartialEq)]
enum Meridian {
    AnteMeridian,
    PostMeridian,
}

#[derive(Debug, Copy, Clone, PartialEq)]
enum TimeComponent {
    Hour,
    Minutes,
    Seconds,
}

impl fmt::Display for TimeComponent {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
        use TimeComponent::*;

        let name = match *self {
            Hour =&gt; "hour",
            Minutes =&gt; "minutes",
            Seconds =&gt; "seconds",
        };
        write!(f, "{}", name)
    }
}

impl FromStr for Meridian {
    type Err = Error;

    fn from_str(s: &amp;str) -&gt; Result&lt;Meridian&gt; {
        match s {
            "AM" =&gt; Ok(Meridian::AnteMeridian),
            "PM" =&gt; Ok(Meridian::PostMeridian),
            _ =&gt; Err(Error::InvalidMeridian(s.to_string())),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
struct TwelveHourTime {
    hour: u8,
    minutes: u8,
    seconds: u8,
    meridian: Meridian,
}

impl FromStr for TwelveHourTime {
    type Err = Error;

    fn from_str(time: &amp;str) -&gt; Result&lt;TwelveHourTime&gt; {
        use Error::*;
        use TimeComponent::*;

        let mut parts = time.splitn(3, ":");

        let hour = parts.next().ok_or(MissingComponent(Hour))?;
        let minutes = parts.next().ok_or(MissingComponent(Minutes))?;
        let seconds_meridian = parts.next().ok_or(MissingComponent(Seconds))?;

        if seconds_meridian.len() &lt; 4 {
            return Err(MissingMeridian);
        }

        let (seconds, meridian) = seconds_meridian.split_at(2);

        let hour = hour.parse().map_err(|e| InvalidComponent(Hour, e))?;
        let minutes = minutes.parse().map_err(|e| InvalidComponent(Minutes, e))?;
        let seconds = seconds.parse().map_err(|e| InvalidComponent(Seconds, e))?;
        let meridian = meridian.parse()?;

        Ok(TwelveHourTime {
            hour: hour,
            minutes: minutes,
            seconds: seconds,
            meridian: meridian,
        })
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
struct TwentyFourHourTime {
    hour: u8,
    minutes: u8,
    seconds: u8,
}

impl From&lt;TwelveHourTime&gt; for TwentyFourHourTime {
    fn from(other: TwelveHourTime) -&gt; Self {
        let hour = match other.meridian {
            Meridian::AnteMeridian =&gt; other.hour,
            Meridian::PostMeridian =&gt; other.hour + 12,
        };

        TwentyFourHourTime {
            hour: hour,
            minutes: other.minutes,
            seconds: other.seconds,
        }
    }
}

impl fmt::Display for TwentyFourHourTime {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
        write!(f, "{:02}:{:02}:{:02}", self.hour, self.minutes, self.seconds)
    }
}

fn main() {
    let mut time = String::new();
    stdin().read_line(&amp;mut time).expect("Unable to read input");

    let time: TwelveHourTime = time.trim().parse().expect("Unable to parse time");
    let time: TwentyFourHourTime = time.into();

    println!("{}", time);
}





  The problem is very simple, but the code seems too lengthy?


I don't suppose I made the length any better! However, I feel that the final code is pretty efficient, and when you start taking error cases into account, I would disagree that the problem is inherently "simple". Parsing text is complicated. You can use tools like regular expressions or parser combinators / generators, but those are just abstractions - the complexity is just hidden from view.

There's still logical aspects here that are strange. For example, the original code does hours % 12, which seems wrong, and my modified code does not, which also seems wrong! It's probably better to throw an error for invalid hourly values.