[Solved] E0619 when using an array of functions


#1

When trying to use an array of functions I get:

error[E0619]: the type of this value must be known in this context

yet to me it seems that the type should be perfectly deducible. Here is the code:

use std::env;

mod p000;  /* pub fn s() -> u64 { 0 }   */
mod p001;  /* pub fn s() -> u64 { ... } */

static S: [fn() -> u64; 2] = [
    p000::s,
    p001::s,
];

fn main() {
    for a in env::args().skip(1) {
        let i = a.parse().unwrap();
        let f = S[i];
        let s = f();  /* error for f() */
        println!("#{} -> {}", i, s);
    }
}

#2

That’s interesting. The real issue is it can’t deduce what i is, but the way the error is reported is definitely confusing (and maybe wrong/buggy).

If you type hint the i, parse::<usize>(), it all goes well.


#3

Thank you! It works now indeed. What adds to the confusion is that I’d definitely expect the compiler to know what is the type of array index.


#4

Yeah. I think the problem is that indexing, in general, can yield whatever type std::ops::Index says it returns and you can implement that trait for many different types of index. So until it knows what that type is, it doesn’t know the output type. It manifests badly here because it reports the error in the “wrong” place.