目前我正在使用这样的代码:
package hello
type object map[string]interface{}
func (o object) get(key string) object {
val, _ := o[key].(object)
return val
}
func (o object) getInt(key string) int {
val, _ := o[key].(int)
return val
}
但问题是,我必须为我想要返回的每种类型编写一个函数。我尝试使用这样的东西:
package hello
type object map[string]interface{}
// syntax error: method must have no type parameters
func (o object) get[T object|int](key string) T {
val, _ := o[key].(T)
return val
}
然后我这样做了:
package hello
type object map[string]interface{}
type token[T object|int] struct {
in object
out T
}
func (t token[T]) get(key string) token[T] {
t.out, _ = t.in[key].(T)
return t
}
可以编译,但由于in永远不会更新,所以我认为我无法为嵌套地图进行链接:
something.get("one").get("two").get("three")
是否可以用泛型做一些事情,得到与我的原始代码相似的结果,但没有复制粘贴功能?
RISEBY