mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-07-26 06:38:42 +00:00
reflect: add Type.String()
This commit is contained in:
committed by
Damian Gryski
parent
7654d86d2c
commit
90af41d089
+35
-1
@@ -59,6 +59,7 @@
|
||||
package reflect
|
||||
|
||||
import (
|
||||
"internal/itoa"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
@@ -487,7 +488,40 @@ func pointerTo(t *rawType) *rawType {
|
||||
}
|
||||
|
||||
func (t *rawType) String() string {
|
||||
return "T"
|
||||
if t.isNamed() {
|
||||
// TODO(dgryski): `main` until pkgPath support lands
|
||||
return "<unknown>" + "." + t.Name()
|
||||
}
|
||||
|
||||
switch t.Kind() {
|
||||
case Chan:
|
||||
return "chan " + t.elem().String()
|
||||
case Pointer:
|
||||
return "*" + t.elem().String()
|
||||
case Slice:
|
||||
return "[]" + t.elem().String()
|
||||
case Array:
|
||||
return "[" + itoa.Itoa(t.Len()) + "]" + t.elem().String()
|
||||
case Map:
|
||||
return "map[" + t.key().String() + "]" + t.elem().String()
|
||||
case Struct:
|
||||
s := "struct {"
|
||||
numField := t.NumField()
|
||||
for i := 0; i < numField; i++ {
|
||||
f := t.rawField(i)
|
||||
s += " " + f.Name + " " + f.Type.String()
|
||||
// every field except the last needs a semicolon
|
||||
if i < numField-1 {
|
||||
s += ";"
|
||||
}
|
||||
}
|
||||
s += " }"
|
||||
return s
|
||||
default:
|
||||
return t.Kind().String()
|
||||
}
|
||||
|
||||
return t.Kind().String()
|
||||
}
|
||||
|
||||
func (t *rawType) Kind() Kind {
|
||||
|
||||
@@ -221,6 +221,23 @@ func TestNamedTypes(t *testing.T) {
|
||||
t.Errorf("TypeOf.Name()=%v, want %v", got, want)
|
||||
}
|
||||
|
||||
if got, want := TypeOf(map[[4]uint16]string{}).String(), "map[[4]uint16]string"; got != want {
|
||||
t.Errorf("Type.String()=%v, want %v", got, want)
|
||||
}
|
||||
|
||||
s := struct {
|
||||
a int8
|
||||
b int8
|
||||
c int8
|
||||
d int8
|
||||
e int8
|
||||
f int32
|
||||
}{}
|
||||
|
||||
if got, want := TypeOf(s).String(), "struct { a int8; b int8; c int8; d int8; e int8; f int32 }"; got != want {
|
||||
t.Errorf("Type.String()=%v, want %v", got, want)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func equal[T comparable](a, b []T) bool {
|
||||
|
||||
Reference in New Issue
Block a user