2

Suppose I am writing a function that takes a bunch of string 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 empty vector?

Is it simpler and more "idiomatic 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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Jim
  • 3,821
  • 1
  • 28
  • 60
  • 8
    Is the distinction between `None` and `Some([])` meaningful? If not, then there's no reason to add `Option`. – kmdreko Jul 18 '23 at 01:25
  • 1
    Returning an empty `Vec` will make the implementation and usage of the function easier. – PitaJ Jul 18 '23 at 01:31

2 Answers2

10

If you're asking if it's acceptable to mindlessly replace returning an empty vector with None, don't - just remove the Option and 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. None may represent "unknown", while Some(vec![]) may represent "known to be empty". Context is important when designing software.

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
1

Depending on the context, it may help to use Option<Vec>:

  • to follow a style or convention (for example there are already a group of interface functions returning Option<_>);
  • for the convenience to pass to other interfaces accepting Options;
  • to suit for some generics of Option<T>;

In other cases, I prefer to return without Option as it's simpler, and in most cases you want None you can use empty Vec instead.

rustyhu
  • 1,912
  • 19
  • 28