Rust code review

fn print_item(item: &str)->Option<bool>{
    if item == "rust"{
        Some(true)
    }else{
        None
    }
}

pub fn main() {
    let item = "python";
    println!("{:?}", print_item(item));
    let item = "rust";
    match print_item(item) {
        Some(e)=>println!("{e:?}"),
        None=>println!("None"),
    }
}

(Playground)

Output:

None
true

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.59s
     Running `target/debug/playground`

The code here seems to compile and run, but it's hard to give code review without knowing what it's for. Is there a use case that you have in mind?

I find your mixing up the way you do things in main() confusing. I would pick one way or the other and stick with it.

pub fn main() {
    let item = "python";
    println!("{:?}", print_item(item));
    let item = "rust";
    println!("{:?}", print_item(item));
   }

or

pub fn main() {
    let item = "python";
    match print_item(item) {
        Some(e)=>println!("{e:?}"),
        None=>println!("None"),
    }
    let item = "rust";
    match print_item(item) {
        Some(e)=>println!("{e:?}"),
        None=>println!("None"),
    }
}

Iā€™d rewrite print_item a little:

fn print_item(item: &str) -> Option<bool> {
    (item == "rust").then_some(true)
}

Option<bool> feels pretty unoptimized tho. Why not just bool, Option(()) or a custom enum?

UPD: I found out that compiler optimizes Option<bool>.

Of course it does, but it's still not clear why it should be used in this context. An Option<bool> has three different values (Some(true), Some(false) and None), yet only two are used. In this case OP should just return a bool.

Also, OP's function name seems to be misleading: print_item indicates that the item is going to be printed (presumably to some stream, stdout, or a printer), yet it is a pure function that doesn't do anything like that.

3 Likes