小编Joh*_*n C的帖子

如何通过成员变量调用函数?

玩弄Rust,我正在将一些代码提取到一个类中.为了使其保持独立但功能分离,我想挂起一个回调函数并稍后调用它.为了简单起见,包括跳过明显的fn new(),我们有类似的东西:

pub struct Toy {
    go: fn(count: i16) -> String,
}

impl Toy {
    fn lets_go(&mut self, n: i16) -> String {
        self.go(n)
    }
}
Run Code Online (Sandbox Code Playgroud)

建筑给了我......

...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)
Run Code Online (Sandbox Code Playgroud)

据推测,有一个特殊的语法(或完全不同的构造)可以理解self.go()调用,但我没有在任何文档中看到类似情况的示例或描述,所以我很欣赏任何方向.

显然,.go 可能是类似仿函数的类,但对Rust来说这似乎不是很惯用.

rust

6
推荐指数
1
解决办法
1574
查看次数

将函数和方法作为参数传递有什么区别?

就像我之前的问题一样,我正在重构一个小型 Rust 项目。与该问题类似,编译器和我在方法和值上的看法也不一致。不过,错误消息非常不同,这似乎可能涉及库,在本例中是hyper 。

/* extern and use directives... */

pub struct WebServer /* with stuff not relevant to the error */;

impl WebServer {
    pub fn serve(&mut self) {
        let server = Server::http(Ipv4Addr(127, 0, 0, 1), 80);
        let mut listening = server.listen(self.return_page).unwrap();
        listening.await();
    }

    fn return_page(&mut self, req: Request, mut res: Response) {
        /* Put the page together */
    }
}
Run Code Online (Sandbox Code Playgroud)

serve()return_page()仅仅是 中的函数时main.rs,它会编译并运行。

但是,如上所述struct,我收到以下错误:

.../src/main.rs:13:48: 13:59 …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
3465
查看次数

标签 统计

rust ×2