问题描述
玩弄 Rust,我将一些代码提取到一个类中.为了保持它独立但独立的功能,我想挂在回调函数上并稍后调用它.为了简单起见,包括跳过明显的fn new()
,我们有类似的东西:
Toying with Rust, I'm extracting some code into a class. To keep it self-contained but separate functionality, I want to hang onto a callback function and call it later. To keep it simple, including skipping the obvious fn new()
, we have something like:
pub struct Toy {
go: fn(count: i16) -> String,
}
impl Toy {
fn lets_go(&mut self, n: i16) -> String {
self.go(n)
}
}
建筑给了我...
...path.../src/toy.rs:7:14: 7:19 error: type `&mut toy::Toy` does not implement any method in scope named `go`
...path.../src/toy.rs:7 self.go(n)
据推测,有一种特殊的语法(或完全不同的构造)可以理解 self.go()
调用,但我没有看到任何示例或类似情况的描述文档,所以我很感激任何指导.
Presumably, there's a special syntax (or entirely different construct) that makes sense of the self.go()
call, but I don't see examples or descriptions of comparable situations in any of the documentation, so I'd appreciate any direction.
显然,.go
可以是一个类似函子的类,但这对于 Rust 来说似乎不太习惯.
Obviously, .go
could be of a functor-like class, but that doesn't seem very idiomatic for Rust.
推荐答案
foo.bar(...)
总是被解析为方法调用,它从不查找字段.这避免了歧义,尤其是在特征方面.可以通过将调用和字段访问分成两个不同的表达式来强制其为字段访问,例如,
foo.bar(...)
is always parsed as a method call, it never looks for fields. This avoids ambiguity, especially with traits. One can force it to be a field access by separating the call and the field access into two distinct expressions, for example,
let f = self.go;
f(n)
或者,更好,只是(self.go)(n)
.
问题 #2392 包括改进这些诊断.
Issue #2392 covers improving these diagnostics.
这篇关于如何通过成员变量调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!