为了账号安全,请及时绑定邮箱和手机立即绑定

嵌套映射的泛型

嵌套映射的泛型

Go
暮色呼如 2022-11-23 15:51:51
目前我正在使用这样的代码:package hellotype 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 hellotype object map[string]interface{}// syntax error: method must have no type parametersfunc (o object) get[T object|int](key string) T {   val, _ := o[key].(T)   return val}然后我这样做了:package hellotype 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")是否可以用泛型做一些事情,得到与我的原始代码相似的结果,但没有复制粘贴功能?
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

我想我明白了。您可以创建一个包装器类型,它包含当前对象以及输出值。如果有人有其他想法,我也对它们感兴趣:


package main


type 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 main


func main() {

   obj := object{

      "one": object{

         "two": object{"three": 3},

      },

   }

   three := newToken[int](obj).get("one").get("two").get("three")

   println(three.value == 3)

}


查看完整回答
反对 回复 2022-11-23
  • 1 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信