Right way to have Function pointers in struct [duplicate]

大兔子大兔子 提交于 2020-01-14 07:37:36

问题


I'm trying to make a struct that has a mutable function pointer. I have it setup so that the function pointer is initialized to a particular function, but rust doesn't 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's 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"));
}

回答1:


It looks like you just have two simple errors in your code. If you change this

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

to this

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

then it works. I don't know why the syntax self.get_func(self, key) doesn't work; it's probably just an oversight in the rust compiler.



来源:https://stackoverflow.com/questions/37370120/right-way-to-have-function-pointers-in-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!