Lazy_static generates compiler error that seems to be ignored when running

Why does compiler generates a warning like so in vscode however, when I run it it works just fine.

error[E0308]: mismatched types
119 |         static ref ADDR: &'static str = default_addr();
    |                          ------------   ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found `String`
    |                          |
    |                          expected `&'static str` because of return type
help: consider borrowing here
119 |         static ref ADDR: &'static str = &setup::net::default_addr();
    |                                         +

    pub fn default_addr() -> &'static str 
        let addr = format!("").into_boxed_str();
    lazy_static! {
        static ref ADDR: &'static str = default_addr();

Are you mixing up what is actually getting called? Because the warning thinks you're returning a String there.

This is a weird implementation though -- why doesn't it just return "" directly?


I don't believe so. But I get a warning with the line getting highlighted, however. when I do run it is just fine. Also by adding the borrow the error in the vscode goes away and it also runs just fine.

Behind scenes the port is getting dynamically discovered, I have simplified it in my example but here is what is behind it.

lazy_static! {
    static ref AVAILABLE_PORT: u16 = {
        for port in 8000..9000 {
            if TcpListener::bind(format!("{}", port)).is_ok() {
                return port;
        panic!("Unable to find an available port in range 8000..9000");

pub fn default_addr() -> &'static str {
    let addr = format!("{}", *AVAILABLE_PORT).into_boxed_str();

That code has a TOCTOU bug. Why not check for a port when you actually need one?


Sounds like maybe an IDE thing. Maybe an older error from when the function had a different signature, was still staying displayed in your vscode? Did you try if after reloading or restarting vscode, the error disappears?

long story short, i have a bunch of unit tests which can't share a port, so i need to randomly find a port that will be free and not chosen by other tests.

restarting, other things don' help. The error is persistent

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.