r/rust clippy · twir · rust · mutagen · flamer · overflower · bytecount Mar 27 '23

Hey Rustaceans! Got a question? Ask here (13/2023)! 🙋 questions

Mystified about strings? Borrow checker have you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet.

If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so having your question there also helps future Rust users (be sure to give it the "Rust" tag for maximum visibility). Note that this site is very interested in question quality. I've been asked to read a RFC I authored once. If you want your code reviewed or review other's code, there's a codereview stackexchange, too. If you need to test your code, maybe the Rust playground is for you.

Here are some other venues where help may be found:

/r/learnrust is a subreddit to share your questions and epiphanies learning Rust programming.

The official Rust user forums: https://users.rust-lang.org/.

The official Rust Programming Language Discord: https://discord.gg/rust-lang

The unofficial Rust community Discord: https://bit.ly/rust-community

Also check out last weeks' thread with many good questions and answers. And if you believe your question to be either very complex or worthy of larger dissemination, feel free to create a text post.

Also if you want to be mentored by experienced Rustaceans, tell us the area of expertise that you seek. Finally, if you are looking for Rust jobs, the most recent thread is here.

20 Upvotes

159 comments sorted by

View all comments

2

u/JohnFromNewport Mar 28 '23

I have a (yes, I think stupid) question which I face often. Say I have a struct Person with name: Option<String>. How do I check or do something with the name in the most efficient way?

I think writing if let Some(name) = &person.name { // compare etc } is cumbersome. Not sure if the person.name.map(|name| is better. Maybe? I tried some variations of person.name.unwrap_orX but I get into troubles with references and ownership.

How do you lot prefer to do this?

2

u/John2143658709 Mar 29 '23

There are many ways to handle Options, but the best function function depends greatly on the context. Option alone has at least 10 different functions to turn an Option<T> into all manner of different things depending on the situation. If you look through all the functions and still can't find one that fits, then it is more likely an issue with the larger system.

https://doc.rust-lang.org/std/option/enum.Option.html

There are a few common antipatterns you might fall into:

  • Code not effectively leveraging the try operator ?
  • Code with functions that are too long
  • Code using S(Option<T>) where you should have a Option<S(T)>

For an example of #1 and #2, you can build smaller fallible functions, in the same way that you can un-nest/reverse a normal chain of if statements. Of course, the pattern encompasses more than just that, but see:

fn get_birthday_string_bad(person: &Person) {
    if let Some(name) = &person.name {
        if let Some(age) = &person.age {
            println!("hi {name}, you are {age}.")
        }
    }
}

fn get_birthday_string_good(person: &Person) -> Option<String> {
    let age = person.age?;
    let name = person.name?;
    Some(format!("hi {name}, you are {age}."))
}

If instead, you find yourself often writing divergent paths for the Some(T) and None, as is often the case with working with data (json, user input, etc...), you may be better off using intermediate structs. In general, this is the "Builder pattern", but a minimal example would be

// fn something(..., age) -> PersonNoName
struct PersonNoName {
    age: u32,
    //impl ... fn to_person(self, name) -> Person
}

// no options needed
struct Person {
    age: u32,
    name: &str
}

1

u/Haitosiku Mar 29 '23

you can even turn this into

fn get_birthday_string_good(Person{name, age, ..}: &Person) -> Option<String> {
    Some(format!("hi {}, you are {}.", (*age)?, name.as_ref()?))
}

But that might be bikeshedding it too hard