Skip to content

again it's a bug #60870

@andy-yx-chen

Description

@andy-yx-chen
static gs : &str = "global str";

fn main() {
    let mut s3 = String::from("Hello, world!");
    let s4 = try_it(&s3[..]);
    println!("{}", s4);
    s3.clear();
    println!("s4={}", s4);
}

fn try_it(s: &str) -> &str {
    println!("{}", s);
    return gs;
}

compile error

error[E0502]: cannot borrow `s3` as mutable because it is also borrowed as immutable
40 |     let s4 = try_it(&s3[..]);
   |                      -- immutable borrow occurs here
41 |     println!("{}", s4);
42 |     s3.clear();
   |     ^^^^^^^^^^ mutable borrow occurs here
43 |     println!("s4={}", s4);
   |                       -- immutable borrow later used here *completely wrong, s4 has nothing to do with s3*

@cramertj 's reply

No, This is not a bug. The elided lifetimes in try_it are assuming that the output &str has the same lifetime as the input &str. To fix this, you can change try_it to -> &'static str.

two points

  1. compiler actually knows whether the returned slice is s3 or not
  2. adding &'static is ugly and cannot solve the problem, such as if(xxx) gs else s4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions