Skip to content

Unexpected behavior with type inference #134854

Open
@zadlg

Description

@zadlg

Hi Rust! 🦀

I tried this code:

struct Foo;
struct Target;

impl From<Target> for Foo {
    fn from(_t: Target) -> Self {
        Self
    }
}


fn may_use_some_type<T>(_t: T) where
    Foo: From<T>
{
}


fn use_another_type<T>(t: T) where
    Foo: From<T>
{
    let other_type = Target;
    may_use_some_type(other_type);
}

I expected to see this happen: rustc compiles the above code successfully.

Instead, this happened: rustc raises the following type error (rustc --crate-type lib test.rs):

error[E0308]: mismatched types
  --> test.rs:21:23
   |
17 | fn use_another_type<T>(t: T) where
   |                     - expected this type parameter
...
21 |     may_use_some_type(other_type);
   |     ----------------- ^^^^^^^^^^ expected type parameter `T`, found `Target`
   |     |
   |     arguments to this function are incorrect
   |
   = note: expected type parameter `T`
                      found struct `Target`
note: function defined here
  --> test.rs:11:4
   |
11 | fn may_use_some_type<T>(_t: T) where
   |    ^^^^^^^^^^^^^^^^^    -----

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.

However, if we change the following:

    may_use_some_type(other_type);

to

    may_use_some_type::<Target>(other_type);

Then, it compiles successfully.

From my understanding, there is no link/dependency between the T of may_use_some_type and the one of use_another_type. Therefore I feel like the type inference system (whatever it is called) is mixing things here.

The where clause form Cond: T may be causing that bug (if it is a bug in the first place), because if we change it to something like T: Send, then it also works.

Meta

rustc --version --verbose:

rustc 1.83.0 (90b35a623 2024-11-26)
binary: rustc
commit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf
commit-date: 2024-11-26
host: x86_64-unknown-linux-gnu
release: 1.83.0
LLVM version: 19.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceC-bugCategory: This is a bug.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