Vector of functions

Hello

I am just experimenting a bit with a basic self made HTTP server. Basically I want to have the following:
A vector consisting of a tuple. The first part of the tuple is a string containing a path. e.g "/" or "/welcome". Then I have a struct called Routes. This struct contains methods for the corresponding paths.

Code:

fn main() {
    let routes : std::vec::Vec<(&'static str, fn(&Routes) -> Result<String, String>)> = vec![
        ("/", Routes::index)
    ];
}

struct Routes;
impl Routes {
    fn index() -> Result<String, String> {
        Ok("OK".into())
    }
}

This is the error I get:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
 --> src/main.rs:3:15
  |
3 |         ("/", Routes::index)
  |               ^^^^^^^^^^^^^ incorrect number of function parameters
  |
  = note: expected fn pointer `for<'a> fn(&'a Routes) -> Result<_, _>`
                found fn item `fn() -> Result<_, _> {Routes::index}`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` (bin "playground") due to previous error
Standard Output

How would I solve this?

struct Routes;
impl Routes {
-   fn index() -> Result<String, String> {
+   fn index(&self) -> Result<String, String> {
        Ok("OK".into())
    }
}

or

fn main() {
    let routes : std::vec::Vec<(&'static str, fn(&Routes) -> Result<String, String>)> = vec![
-       ("/", Routes::index)
+       ("/", |_r| Routes::index())
    ];
}
3 Likes

Alright thanks. Is it different if index() would be async?

Yes that's different. For storing async fn one would typically turn the return type into BoxFuture and you'd need some light closure wrapper to make the conversion.

Rust Playground

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.