rust-lang-nursery / lazy-static.rs

A small macro for defining lazy evaluated static variables in Rust.
Apache License 2.0
1.9k stars 111 forks source link

Questions about cannot borrow data in a `&` reference as mutable #149

Closed pili2026 closed 5 years ago

pili2026 commented 5 years ago

When I used lazy_static! to construct a connection, I added a new api => set_load_balance_round_robin().

The code is as follows:

lazy_static! {
    static ref SESSION: Session = {
        let args: Vec<String> = env::args().collect();
        Cluster::default()
            .set_contact_points(&args[1])
                .expect("Failed to set_contact_points")
            .set_port(9042)
                .expect("Failed to set_port")
            .set_num_threads_io(8)
                .expect("Failed to set_num_threads_io")
            .set_load_balance_round_robin()
            .connect()
                .expect("Failed to connect to the cluster")
    };
}

But it produces the following error:

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/main.rs:53:9
   |
53 | /         Cluster::default()
54 | |             .set_contact_points(&args[1])
55 | |                 .expect("Failed to set_contact_points")
56 | |             .set_port(9042)
...  |
59 | |                 .expect("Failed to set_num_threads_io")
60 | |             .set_load_balance_round_robin()
   | |___________________________________________^ cannot borrow as mutable

The .set_load_balance_round_robin() source code:

    pub fn set_load_balance_round_robin(&mut self) -> &Self {
        unsafe {
            cass_cluster_set_load_balance_round_robin(self.0);
            self

        }
    }

Is there a way to solve this?

dtolnay commented 5 years ago

This looks like a bug in set_load_balance_round_robin. Seems like it should return &mut Self. I am closing the issue because it doesn't look like something specific to lazy_static.