donglun4521 2015-04-20 12:32
浏览 34
已采纳

使用功能指针作为键进行映射

I recently used a map in one of my golang projects, that had function pointers as keys like this:

map[*functiontype] somestructtype

One of my colleagues said this was a bad idea, so now I am unsure of this being feasible. I initially deemed it ok, because method pointers can be checked for equality and are immutable. Can someone provide some reasoning on that matter?

Complete example:

package main

import "fmt"

type s struct {
    string
}

type f func() string
func func1() string { return "func 1" }
func func2() string { return "func 2" }

func main() {
    // make two functions and two pointers to them
    f1, f2 := func1, func2
    p1, p2 := (*f)(&f1), (*f)(&f2)

    // make a map of their function pointers
    m := make(map[*f]s)
    m[p1] = s{"struct 1"}
    m[p2] = s{"struct 2"}

    // print out the mapping
    printmapping(m, p1, p2)

    // reverse the pointers and have that printed
    p1, p2 = (*f)(&f2), (*f)(&f1)
    printmapping(m, p1, p2)
}

func printmapping(m map[*f]s, p1, p2 *f) {
    fmt.Println("pointer 1:", m[(*f)(p1)])
    fmt.Println("pointer 2:", m[(*f)(p2)])
}
  • 写回答

2条回答 默认 最新

  • dongxing5525 2015-04-20 12:39
    关注

    If the key type is a pointer to a function type (such as *func()) then it's totally fine and the semantics are as expected: equal pointers are equal keys.

    However, looking up the values in the map may not work out as you may expect: example. Here &f takes the address of the local variable, which is never the same for different invocations of Add and Find. The following of course could be useful: http://play.golang.org/p/F9jyUxzJhz


    If it is not a pointer, it's a bad idea because it's impossible from Go 1 onwards. According to the language specification (live demo):

    The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice.

    == and != aren't defined for functions since the problem of comparing functions for equality is undecidable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据