Skip to content

Compiler error when trying to access function pointer in struct. #33784

Closed
@damnMeddlingKid

Description

@damnMeddlingKid

running rustc 1.8.0 (db29394 2016-04-11).

I have a simple struct that contains a function pointer named get_func and when i try to access the function pointer in an implemented method 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)
                         ^~~~~~~~

heres the code for reproducing

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

oddly enough replacing self.get_func(self, key) with (self.get_func)(self, key) fixes the error, so I'm calling this a compiler bug.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions