So this is just a curiosity question.
If I want to return unit, which is better practice?
|> ignore
or
()
There's probably other ways as well. I just want to know what's best, considering these:
I think you are comparing things that are not quite comparable here. The ()
value lets you create the unit value, while |> ignore
is what you can use to ignore some other result. The two are not exactly the same:
If you are calling a function and you want to ignore the result, you can write just:
doStuff () |> ignore
But doing the same with ()
would require you to either ignore the warning:
doStuff () // warning: Result is ignored
()
... or you could assign the result to an ignore pattern _
using let
binding:
let _ = doStuff ()
()
So, in this case, using ignore
is better - it is inlined, so it has no performance implications and it leads to code that is easier to read.
That said, there are cases where you just need to create a unit value and then ()
is what you need (and there is no obvious way ignore
would let you do the same). For example:
match optMessage with
| Some message -> printfn "ANNOUNCEMENT: %s" message
| None -> ()
You could replace ()
with 42 |> ignore
to get the same result, but it would be silly!
ignore
is an inlined function so both will produce exactly the same IL.
ignore
is more explicit and therefore more readable, and that's why it exists, so you should probably prefer that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With