diff options
author | Damian Gryski <[email protected]> | 2023-02-25 13:37:46 -0800 |
---|---|---|
committer | Ayke <[email protected]> | 2023-02-28 13:10:40 -0800 |
commit | 9541525402bd50c49336ea90b2ceb96cd0f9376c (patch) | |
tree | 89634b4d9eeb81547056fc05dfa99e3c9a8d39f4 | |
parent | 60a93e8e2d24525eb5a8084d054b06c5c0684672 (diff) | |
download | tinygo-9541525402bd50c49336ea90b2ceb96cd0f9376c.tar.gz tinygo-9541525402bd50c49336ea90b2ceb96cd0f9376c.zip |
reflect: add Type.Elem() and Type.Key() for Maps
-rw-r--r-- | src/reflect/type.go | 16 | ||||
-rw-r--r-- | src/reflect/value_test.go | 15 |
2 files changed, 27 insertions, 4 deletions
diff --git a/src/reflect/type.go b/src/reflect/type.go index 3998adc02..1f0776098 100644 --- a/src/reflect/type.go +++ b/src/reflect/type.go @@ -481,11 +481,19 @@ func (t *rawType) elem() *rawType { switch underlying.Kind() { case Pointer: return (*ptrType)(unsafe.Pointer(underlying)).elem - case Chan, Slice, Array: + case Chan, Slice, Array, Map: return (*elemType)(unsafe.Pointer(underlying)).elem - default: // not implemented: Map - panic("unimplemented: (reflect.Type).Elem()") + default: + panic(&TypeError{"Elem"}) + } +} + +func (t *rawType) key() *rawType { + underlying := t.underlying() + if underlying.Kind() != Map { + panic(&TypeError{"Key"}) } + return (*mapType)(unsafe.Pointer(underlying)).key } // Field returns the type of the i'th field of this struct type. It panics if t @@ -806,7 +814,7 @@ func (t *rawType) Name() string { } func (t *rawType) Key() Type { - panic("unimplemented: (reflect.Type).Key()") + return t.key() } func (t rawType) In(i int) Type { diff --git a/src/reflect/value_test.go b/src/reflect/value_test.go index 5698ede55..d3d0aa0af 100644 --- a/src/reflect/value_test.go +++ b/src/reflect/value_test.go @@ -30,3 +30,18 @@ func TestIndirectPointers(t *testing.T) { t.Errorf("bad indirect array index via reflect") } } + +func TestMap(t *testing.T) { + + m := make(map[string]int) + + mtyp := TypeOf(m) + + if got, want := mtyp.Key().Kind().String(), "string"; got != want { + t.Errorf("m.Type().Key().String()=%q, want %q", got, want) + } + + if got, want := mtyp.Elem().Kind().String(), "int"; got != want { + t.Errorf("m.Elem().String()=%q, want %q", got, want) + } +} |