DEV Community

loading...

Discussion on: Rust and Go department directories

Collapse
coolshaurya profile image
Shaurya

In Rust, the last expression of a function is automatically returned so a lot of returns in your code can be easily removed. Also, within an impl block you can use Self to refer to the type you're implementing stuff on.

For example, in

    fn new() -> Organisation {
        return Organisation {
            departments: HashMap::new(),
        }
    }
Enter fullscreen mode Exit fullscreen mode

you can remove the return and use Self to make it

    fn new() -> Self {
        Self {
            departments: HashMap::new(),
        }
    }
Enter fullscreen mode Exit fullscreen mode

Similarly you can do -

fn parse_command(cmd: &mut String, org: &mut Organisation) -> Action {
    let parts: Vec<&str> = cmd.split_whitespace().collect();
    if parts.len() == 0 {
        return Action::Failure(String::from("No commands found"));
    }

    match parts[0] {
        "add" => add_command(parts, org),
        "help" => help_command(),
        "list" => list_command(parts, org),
        "quit" => Action::Quit,
        _ => Action::Failure(format!("Unknown command {}", parts[0])),
    }
}
Enter fullscreen mode Exit fullscreen mode

match is also an expression so your list_command fn can be -

fn list_command(parts: Vec<&str>, org: &mut Organisation) -> Action {
    match parts.len() {
        1 => {
            org.print();
            Action::Done
        }
        2 => {
            org.print_department(String::from(parts[1]));
            Action::Done
        }
        _ =>  Action::Failure(String::from("Unexpected usage.  Expect 0 or 1 parameters for list"))
}
Enter fullscreen mode Exit fullscreen mode
Collapse
mark_saward profile image
Mark Saward Author

Thanks for those tips. I was aware that you can return without using the keyword 'return', but old habits kicked in when I wrote this :)

Thinking about it, the explicitness of having the 'return' keyword is something I find nice, to quickly scan a function to easily identify the places it returns.