Skip to content

The inference problem caused by Option::filter on function result #130026

Open
@A4-Tacks

Description

@A4-Tacks

no error case:

pub fn true_pred<T>(_: T) -> bool {
    true
}

pub fn foo<T, F>(ele: &T, mut f: F) -> Option<& T>
where F: FnMut(&T) -> bool,
{
    [ele].into_iter()
        .fold(None, |acc, _| {
            acc.filter(|min| f(min))
        })
        //.filter(true_pred) // error!
}

error case:

pub fn true_pred<T>(_: T) -> bool {
    true
}

pub fn foo<T, F>(ele: &T, mut f: F) -> Option<& T>
where F: FnMut(&T) -> bool,
{
    [ele].into_iter()
        .fold(None, |acc, _| {
            acc.filter(|min| f(min))
        })
        .filter(true_pred) // error!
}

cargo check output:

error[E0308]: mismatched types
  --> src/lib.rs:8:5
   |
5  |   pub fn foo<T, F>(ele: &T, mut f: F) -> Option<& T>
   |              - found this type parameter ----------- expected `Option<&T>` because of return type
...
8  | /     [ele].into_iter()
9  | |         .fold(None, |acc, _| {
10 | |             acc.filter(|min| f(min))
11 | |         })
12 | |         .filter(true_pred) // error!
   | |__________________________^ expected `Option<&T>`, found `Option<T>`
   |
   = note: expected enum `Option<&_>`
              found enum `Option<_>`
help: try using `.as_ref()` to convert `Option<T>` to `Option<&T>`
   |
12 |         .filter(true_pred).as_ref() // error!
   |                           +++++++++

For more information about this error, try `rustc --explain E0308`.
error: could not compile `test1` (lib) due to 1 previous error

rustc version:

rustc 1.82.0-nightly (1f12b9b0f 2024-08-27)
binary: rustc
commit-hash: 1f12b9b0fdbe735968ac002792a720f0ba4faca6
commit-date: 2024-08-27
host: aarch64-unknown-linux-gnu
release: 1.82.0-nightly
LLVM version: 19.1.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceA-result-optionArea: Result and Option combinatorsC-discussionCategory: Discussion or questions that doesn't represent real issues.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions