在结构中使用函数指针的正确方法 [英] Right way to have Function pointers in struct

查看:28
本文介绍了在结构中使用函数指针的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有可变函数指针的结构.我设置了它,以便将函数指针初始化为特定函数,但是当我尝试使用它时,rust 无法识别该指针.

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.

我明白了

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)
                         ^~~~~~~~

这是我的代码

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"));
}

推荐答案

看起来您的代码中只有两个简单的错误.如果你改变这个

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)
}

到这里

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

然后就可以了.我不知道为什么语法 self.get_func(self, key) 不起作用;这可能只是 Rust 编译器的疏忽.

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.

这篇关于在结构中使用函数指针的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆