【发布时间】:2016-12-08 00:29:14
【问题描述】:
这是一个更高级别的问题,但是我不确定应该使用 Rust 的哪些功能来优化问题。
在编写具有工具 API 的图形应用程序的第一步时,我们可能希望传入一个context 参数,它公开应用程序的各个部分:
// Where the data lives.
struct Application {
preferences: Preferences,
windows: Vec<Windows>,
documents: Vec<Document>,
}
// A view on the data to pass to tool-code.
struct AppContext {
preferences: &Preferences, // immutable
window: &Window, // immutable
doc: &Document, // mutable
// ... real world use case has more vars ...
}
// example use
fn some_tool_uppercase(context: &mut AppContext, options: &ToolOptions) {
// random example
for w in context.document.words {
w.to_uppercase();
}
context.window.redraw_tag();
}
在写这篇文章时,我遇到了借用检查器的问题,因为该文档还存储在其他文档的列表中 - 导致它同时在两个地方是可变的。
只是为了编译我的程序,目前我正在从列表中删除文档,运行该工具,然后在工具完成后将其添加回文档列表中。
虽然在某些情况下可以传递多个参数,但上面的示例被简化了。将上下文的每个成员都作为参数传递是不切实际的。
应如何将应用程序的上下文包装成可以传递到工具代码中的类型,而不会给借用检查器带来麻烦?
【问题讨论】:
标签: rust borrow-checker