The right way to create function pointers in a structure

I am trying to create a structure that has a mutable function pointer. I have a setting, so that the function pointer is initialized with a specific function, but the rust does not recognize the pointer when I try to use it.

I get

hello.rs:24:14: 24:22 error: no method named `get_func` found for type `&Container` in the current scope hello.rs:24 self.get_func(self, key) ^~~~~~~~ 

here is my code

 use std::collections::HashMap; struct Container { field: HashMap<String, i32>, get_func: fn(&Container, &str) -> i32 } fn regular_get(obj: &Container, key: &str) -> i32 { obj.field[key] } impl Container { fn new(val: HashMap<String, i32>) -> Container { Container { field: val, get_func: regular_get } } fn get(&self, key: &str) -> i32 { self.get_func(self, key) } } fn main() { let mut c:HashMap<String, i32> = HashMap::new(); c.insert("dog".to_string(), 123); let s = Container::new(c); println!("{} {}", 123, s.get("dog")); } 
+5
source share
1 answer

It looks like you have only two errors in the code. If you change this

 fn get(&self, key: &str) -> Container { self.get_func(self, key) } 

to that

 fn get(&self, key: &str) -> i32 { (self.get_func)(self, key) } 

then it works. I do not know why the syntax self.get_func(self, key) does not work; this is probably just an oversight in the rust compiler.

+4
source

All Articles