reflect: add Type.Elem() and Type.Key() for Maps
Этот коммит содержится в:
родитель
60a93e8e2d
коммит
9541525402
2 изменённых файлов: 27 добавлений и 4 удалений
|
@ -481,13 +481,21 @@ 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
|
||||
// is not a struct type.
|
||||
func (t *rawType) Field(i int) StructField {
|
||||
|
@ -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 {
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
Загрузка…
Создание таблицы
Сослаться в новой задаче