What is wrong this line of code?

fn main() {
	println!("{:?}", std::option::Option::filter("hello world", |a : &str| a.len() == 5))


i wanna write it that way but it says size not known

How it is expected to work, first of all? Option::filter is a method, its first argument is self, i.e. Option<T>.


It's usually a good idea to also include:

  • The error message you're hitting
  • Maybe a link to the playground, then people can easily replicate it and may be able to help

Copied it to the playground: Rust Playground

I give you that the first error is indeed a bit unhelpful.
But if you look a bit further you'll find:

error[E0308]: mismatched types
  = note:   expected enum `Option<str>`
          found reference `&'static str`

Option::filter expects self as its first argument, so it must be of type Option<T>
That gets you to

println!("{:?}", Option::filter(Some("hello world"), |a : &str| a.len() == 5))

which will give you the error:

  = note: expected closure signature `for<'a> fn(&'a &str) -> _`
             found closure signature `for<'a> fn(&'a str) -> _`

And that's because P: FnOnce(&T) -> bool.
And your T = &str.
If you then try with |a: &&str| ... it will work. Or you can just leave out the type annotation there.


please i need answer i am stuck

There have been answers within 10 minutes of your initial post. So ... uhm ... read those first


That's on you then and there's not much we can help you with anymore, sorry.


It is completely unclear what you are even trying to do.

You are calling a function that is a method of Option (ie. it's first argument is Option<_>) on a type that is clearly not Option (&str).

Your filter condition looks like you want to restrict to something that has 5 characters. The words "hello" and "world" both have 5 characters. Maybe you are trying to split your string on whitespace and filter to words that have 5 characters – I have no idea if that is actually what you are after. But if so, then Option::filter isn't going to help you.

You probably wanted to use the str::split_whitespace() method in this case, and filter the resulting iterator.


Certainly you have answers to your question there. Your question was "What is wrong with this line of code" and people have explained why it will not compile.

I suspect that was not the question you really meant to ask. It would help people help you if you would say what it is you actually want to achieve with that code. Otherwise people have to guess at what your real problem is, which of course is likely to be unhelpful and a waste of time.

So, what are you actually trying to do with that code?


i fixed the issue

I'm curious. What was it supposed to do? How did you fix it?

it supposes to add extra check on some or none and i fixed it by creating an option type because filter is defined for option type

1 Like

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.