Suppose I am writing a function that takes a bunch of strings and filters out the "bad" ones.
The function then returns some strings, but there is a chance that all the strings are filtered out.
So I am wondering, should I use to Option here? I could see it making sense that the function either returns the None option variant when all strings are "bad", and it returns the Some variant when the strings are "good".
The function signature could look something like this:
pub fn filter_strings(inputs: Vec<String>) -> Option<Vec<String>> {
// Todo...
}
But is there really any point in making this an Option?
Would this just make things unnecessarily more complicated since the consumer kind of needs to now check for the None variant and also for the case where it returns Some with an empty vector?
Is it simpler and more "idiomatic" in Rust to just return a vector of strings here?
pub fn filter_strings(inputs: Vec<String>) -> Vec<String> {
// Todo...
}
Or is there some advantage to using Option here that I am missing?
If you're asking if it's acceptable to mindlessly replace returning an empty vector with
None, don't - just remove theOptionand return an empty vector. This makes the code that is using the return value a lot easier - they don't have to handle the empty vector specially when there is no reason to. Empty vectors do not allocate any memory from the heap, so there's not even a performance reason.However, there may be cases where the distinction is useful.
Nonemay represent "unknown", whileSome(vec![])may represent "known to be empty". Context is important when designing software.