【发布时间】:2018-07-20 22:22:36
【问题描述】:
如何在闭包中调用方法? get_access_token 方法可以根据self.get_base_url() 设置新的访问令牌:
fn fetch_access_token(_base_url: &String) -> String {
String::new()
}
fn get_env_url() -> String {
String::new()
}
pub struct App {
pub base_url: Option<String>,
pub access_token: Option<String>,
}
impl App {
pub fn new() -> App {
App {
base_url: None,
access_token: None,
}
}
pub fn get_base_url(&mut self) -> &String {
self.base_url.get_or_insert_with(|| get_env_url())
}
pub fn get_access_token(&mut self) -> &String {
self.access_token
.get_or_insert_with(|| fetch_access_token(self.get_base_url()))
}
}
fn main() {}
错误:
Rust 2015
error[E0500]: closure requires unique access to `self` but `self.access_token` is already borrowed
--> src/main.rs:26:33
|
25 | self.access_token
| ----------------- borrow occurs here
26 | .get_or_insert_with(|| fetch_access_token(self.get_base_url()))
| ^^ ---- borrow occurs due to use of `self` in closure
| |
| closure construction occurs here
27 | }
| - borrow ends here
Rust 2018
error[E0501]: cannot borrow `self.access_token` as mutable because previous closure requires unique access
--> src/main.rs:25:9
|
25 | / self.access_token
26 | | .get_or_insert_with(|| fetch_access_token(self.get_base_url()))
| |______________------------------_--____________________----________________^ second borrow occurs here
| | | |
| | | first borrow occurs due to use of `self` in closure
| | closure construction occurs here
| first borrow later used by call
error[E0500]: closure requires unique access to `self` but it is already borrowed
--> src/main.rs:26:33
|
24 | pub fn get_access_token(&mut self) -> &String {
| - let's call the lifetime of this reference `'1`
25 | self.access_token
| -----------------
| |
| _________borrow occurs here
| |
26 | | .get_or_insert_with(|| fetch_access_token(self.get_base_url()))
| |_________________________________^^____________________----________________- returning this value requires that `self.access_token` is borrowed for `'1`
| | |
| | second borrow occurs due to use of `self` in closure
| closure construction occurs here
【问题讨论】:
-
fn get_*(&mut self)- 这不是 getter 通常的工作方式。如何将字段设为私有,并将它们初始化为您正在寻找的默认值?也不要使用&String- 请改用&str。 -
也许vorner.github.io/difficult.html#rust-is-different 对你来说是一本好书。 TLDR:你正试图以你习惯的方式解决问题,但它不适合 Rust - 如果你告诉我们更多关于实际问题的信息,你可能会得到关于 Rust 解决问题的更好的答案。
-
谢谢大家。这是来自 IRC #rust-beginners 的解决方案。
Rust Play Ground Code Link 的代码示例 -
@Aqrun 请不要将答案放在评论中。欢迎您在下面添加您自己的答案。如果你觉得你不应该把别人的答案归功于别人(例如 IRC 上的任何人),你可以选择将答案设为“社区 wiki”。
标签: rust closures borrow-checker mutability