嵌套映射的泛型

目前我正在使用这样的代码:


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")

是否可以用泛型做一些事情,得到与我的原始代码相似的结果,但没有复制粘贴功能?


暮色呼如
浏览 71回答 1
1回答

RISEBY

我想我明白了。您可以创建一个包装器类型,它包含当前对象以及输出值。如果有人有其他想法,我也对它们感兴趣:package maintype object map[string]interface{}type token[T any] struct {   object   value T}func newToken[T any](m object) token[T] {   return token[T]{object: m}}func (t token[T]) get(key string) token[T] {   switch val := t.object[key].(type) {   case object:      t.object = val   case T:      t.value = val   }   return t}例子:package mainfunc main() {   obj := object{      "one": object{         "two": object{"three": 3},      },   }   three := newToken[int](obj).get("one").get("two").get("three")   println(three.value == 3)}
打开App,查看更多内容
随时随地看视频慕课网APP