Skip to content

Confusing mismatched type error #43608

@joshlf

Description

@joshlf

If you forget to put a semicolon after the last expression in the body of a function that returns no values, rustc will infer that the type of the expression should be (). If the programmer didn't intend to return a value, but merely forgot to type a semicolon, the resulting error can be confusing. Consider, for example, the following toy program:

use std::ptr;

fn main() {
    let a = 0;
    ptr::read(&a)
}

This produces the following error message:

error[E0308]: mismatched types
 --> src/main.rs:5:15
  |
5 |     ptr::read(&a)
  |               ^^ expected (), found integral variable
  |
  = note: expected type `*const ()`
             found type `&{integer}`

In this simple example, it may be obvious, but in the somewhat more complicated code I was working with that led me to this issue, I spent a decent amount of time trying to figure out why I was supposedly passing a pointer to () to mem::replace, thus causing the type of the second argument to replace to fail to unify. It took me a while to figure out that this was actually the culprit.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.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