Skip to content

Compiler can't infer &str type when &String is inserted first in a collection with tuples #129358

@zkkv

Description

@zkkv

Description: compiler can't infer &str type when String is inserted first in a collection with tuples.

Steps to reproduce: create a new array and fill it with tuples, where one of the elements is a string literal and one is a variable of type &String. Depending one the order, it might or might not compile because type can't be inferred.

let s = &String::from("foo");

let arr1 = [(1, s), (2, "bar")];  // This line contains a compilation error 
let arr2 = [(2, "bar"), (1, s)];  // Does compile; inferred type is [(i32, &str); 2]

Error message:

error[E0308]: mismatched types
   |
   |     let arr1 = [(1, s), (2, "bar")];
   |                             ^^^^^ expected `&String`, found `&str`
   |
   = note: expected reference `&String`
              found reference `&'static str`

Rust compiler version: rustc 1.80.1 (3f5fd8dd4 2024-08-06)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceT-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