Skip to content

Misplaced "type of this value must be known ..." error #36598

Description

@bnordbo

In a transformation sequence, I got a type inference error on the first function call, while the error was actually later (and below) in the chain. This was very confusing, in particular since the offending line was not shown in the error message. This could be a duplicate of #36495, or a more general issue not related to type inference.

As it should, rustc 1.11.0 on OS X fails to build the following code:

fn fail(v: Vec<u32>) -> Option<Box<Vec<u32>>> {
    v.iter()
        .map(|x| Some(*x))
        .collect()
        .map(Box::new)
}

fn main() {
    fail(vec![1, 2, 3]);
}

The error message is:

/tmp/err.rs:2:5: 5:23 error: the type of this value must be known in this context
/tmp/err.rs:2     v.iter()
                  ^
error: aborting due to previous error

On nightly the error report is nicer, but no more helpful. The fix, which is obvious once one decides to ignore the line indication from rustc, is to add a type annotation to collect():

fn fail(v: Vec<u32>) -> Option<Box<Vec<u32>>> {
    v.iter()
        .map(|x| Some(*x))
        .collect::<Option<_>>()
        .map(Box::new)
}

fn main() {
    fail(vec![1, 2, 3]);
}

After poking around a bit, I suspect that this may be a more general issue related to how rustc determines the offending line number. For instance, the error message from the compiler has the same problem, while the error is "mismatched types":

fn fail(v: Vec<u32>) -> Option<Vec<u32>> {
    v.iter()
        .map(|x| Some(*x))
}

fn main() {
    fail(vec![1, 2, 3]);
}
/tmp/err.rs:2:5: 3:27 error: mismatched types [E0308]
/tmp/err.rs:2     v.iter()
                  ^

[...]

While this is the kind of thing that only bites you once, it can utterly confuse a beginner. It is particularly perplexing in more complex, multi-line expressions. One could of course argue that the error location is correct as it points to the flawed expression, but that does not really help. Perhaps indicating where in the expression the error lies would be better, e.g (using the new and much better error message style from nightly)?

error: the type of this value must be known in this context
 --> /tmp/err.rs:2:5
  |
2 |     v.iter()
3 |         .map(|x| Some(*x))
4 |         .collect()
  |         ^

error: aborting due to previous error

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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