如何在内部块中调用成员方法,并对self进行可变引用

时间:2017-12-03 12:03:44

标签: rust

class Sync { private Writer w1, w2; private Object whatEver; public Sync() { w1 = new Writer(); w2 = new Writer(); whatEver = new Object(); } public void go() { synchronized (whatEver) { w1.log(Thread.currentThread().getName() + "...1"); //!All threads must performance parallel, but they do it consistently. w2.log(Thread.currentThread().getName() + "...2"); //All threads must performance parallel, and they do it. } } } 有一个修改其内容的成员方法(Flow),因此需要change_conn_routes()引用。

要运行,此方法需要调用另一个不修改任何内容的成员方法(&mut self),因此具有get_port()引用。这不会编译。

&self

playground

导致此编译器错误:

struct Conn {
    name: String,
    route: String,
}

struct Flow {
    conns: Option<Vec<Conn>>,
    port: String
}

impl Flow {
    // This method does not modify anything so if possible I'd like it to not
    // need a mutable reference to self.
    fn get_port(&self, _name: &str) -> String {
        // In real program the value of name is actually used - simplified here
        format!("{}", self.port)
    }

    // This method changes the contents of self.conns so reference to self must
    // be mutable. To do so, it needs information from another member function of self
    fn change_conn_routes(&mut self) {
        if let Some(ref mut conns) = self.conns {
            for conn in conns {
                conn.route = format!("{}", self.get_port(&conn.name));
            }
        }
    }
}

fn main() {
    let conns = Some(vec!(Conn{ route: "abc".to_string(), name: "conn1".to_string() }));
    let port = "123".to_string();
    let mut flow = Flow{ conns, port };

    flow.change_conn_routes();

    println!("{}", flow.conns.unwrap()[0].route);
}

0 个答案:

没有答案