Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use function as map's key

How to use function as map's key? for example:

type Action func(int)
func test(a int) { }
func test2(a int) { }

func main() {
  x := map[Action]bool{}
  x[test] = true
  x[test2] = false
}

those code would show an error: invalid map key type Action

like image 548
Kokizzu Avatar asked Dec 03 '14 08:12

Kokizzu


People also ask

Can map keys be functions?

A Map 's keys can be any value (including functions, objects, or any primitive). The keys of an Object must be either a String or a Symbol . The keys in Map are ordered in a simple, straightforward way: A Map object iterates entries, keys, and values in the order of entry insertion.

How do you pass a map key?

One solution is to build a hash table that will look like: { key1: Array('all values of key1'), key2: Array('all values of key2'), ...} Then use this hash table to get result quickly.

How to get Map key in JavaScript?

To get the keys of a Map object, you use the keys() method. The keys() returns a new iterator object that contains the keys of elements in the map.

How to get key and value of a map in JavaScript?

To get value for a specific key in Map in JavaScript, call get() method on this Map and pass the specific key as argument. get() method returns the corresponding value for given key, if present. If the specified key is not present, then get() returns undefined.


1 Answers

You cannot use a function as a map key. The language specification clearly says:

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.

like image 150
Tore Olsen Avatar answered Oct 21 '22 16:10

Tore Olsen