嵌套映射的通用类型
时间:2024-02-10
浏览:317
作者:佚名
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《嵌套映射的通用类型》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
问题内容
目前我正在使用这样的代码:
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")
是否可以使用泛型做一些事情,给出与我的原始代码类似的结果,但没有复制粘贴功能?
正确答案
我想我已经明白了。您可以创建一个包装类型,它保存当前的 对象以及输出值。如果有人有其他想法,我很感兴趣 其中也包括:
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)
}今天关于《嵌套映射的通用类型》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
