Skip to content

Cannot infer type in test from section 12.4 of rust book v2 #45164

Open
@ghost

Description

Hello everyone!
I'm learning Rust now using this book and faced strange(as for me) error on section 12.4 when running tests.

You can reproduce a bug with next snippet of code

pub fn search<'a> (q: &str, text: &'a str) -> Vec<&'a str> {
    text.lines().filter(|line| line.contains(q)).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_should_compile_but_it_doesnt () {
        let q = "queryABCD";
        let t = "text with query";
        assert_eq!( vec![], search(q, t) );
    }
}

// error[E0282]: type annotations needed
//   --> src/lib.rs:13:21
//    |
// 13 |         assert_eq!( vec![], search(q, t) );
//    |                     ^^^^^^ cannot infer type for `T`
//    |
//    = note: this error originates in a macro outside of the current crate

However, it's fairly obvious that compiler knows the type annotation that must be infered from vec![] macro. Next snippet makes it clear

pub fn search<'a> (q: &str, text: &'a str) -> Vec<&'a str> {
    text.lines().filter(|line| line.contains(q)).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_should_compile_but_it_doesnt () {
        let q = "queryABCD";
        let t = "text with query";
        assert_eq!( 333, search(q, t) );
    }
}

// error[E0277]: the trait bound `{integer}: std::cmp::PartialEq<std::vec::Vec<&str>>` is not satisfied
//   --> src/lib.rs:13:9
//    |
// 13 |         assert_eq!( 333, search(q, t) );
//    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't compare `{integer}` with `std::vec::Vec<&str>`
//    |
//    = help: the trait `std::cmp::PartialEq<std::vec::Vec<&str>>` is not implemented for `{integer}`
//    = note: this error originates in a macro outside of the current crate

I think it's a bug but not sure since I'm novice in rust. I tried different toolchains, specifically 1.16, 1.18, 1.20(stable) and nightly and got the same result.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-inferenceArea: Type inferenceC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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