nepero
December 31, 2022, 9:22am
1
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"),
}
}
Miiao
December 31, 2022, 11:44pm
4
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>
.
leob
January 1, 2023, 1:39pm
5
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.
4 Likes
system
Closed
April 1, 2023, 1:40pm
6
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.