Automatic Type Assertion In Go

huangapple go评论92阅读模式
英文:

Automatic Type Assertion In Go

问题

请稍等,我会为您翻译这段代码。

英文:

Take this sample of code (playground):

package main

import (
  "fmt"
)

type Foo struct {
  Name string
}

var data = make(map[string]interface{})

func main() {
  data["foo"] = &Foo{"John"}

  foo := data["foo"].(*Foo)

  fmt.Println(foo.Name)
}

When I add something to data, the type turns into an interface{}, so when I later retrieve that value I have to assert the original type back onto it. Is there a way to, for example, define a getter function for data which will automagically assert the type?

答案1

得分: 3

不是真的,除非你使用reflect并尝试以这种方式获取接口的类型。

但是惯用的(也更快的)方式仍然是type assertion(一种在运行时必须进行检查的“类型转换”,因为data只包含interface{}值)。

如果data引用的是特定接口(而不是通用的interface{}),就像我在这里提到的那样,那么你可以直接在其上定义一个Name()方法。

英文:

Not really, unless you turn to reflect and try to get the type of the interface that way.

But the idiomatic (and faster) way remains the type assertion (a "type conversion" which must be checked at runtime, since data only contains interface{} values).

If data were to reference a specific interface (instead of the generic interface{} one), like I mentioned here, then you could use a Name() method defined directly on it.

答案2

得分: 2

你可以像这样做,但是你可能需要考虑你的设计...很少有情况下你需要这样做。

package main

import (
	"fmt"
)

type GenericMap map[string]interface{}

func (gm GenericMap) GetString(key string) string {
	return gm[key].(string)
}

func (gm GenericMap) GetFoo(key string) *Foo {
	return gm[key].(*Foo)
}

func (gm GenericMap) GetInt(key string) int {
	return gm[key].(int)
}

var data = make(GenericMap)

type Foo struct {
	Name string
}

func main() {
	data["foo"] = &Foo{"John"}

	foo := data.GetFoo("foo")

	fmt.Println(foo.Name)
}

你可能想要添加错误检查,以防键不存在或不是预期的类型。

英文:

You can do something like this, but you might want to think about your design.. It is very rare that you need to do this kind of things.

http://play.golang.org/p/qPSxRoozaM

package main

import (
	"fmt"
)

type GenericMap map[string]interface{}

func (gm GenericMap) GetString(key string) string {
	return gm[key].(string)
}

func (gm GenericMap) GetFoo(key string) *Foo {
	return gm[key].(*Foo)
}

func (gm GenericMap) GetInt(key string) int {
	return gm[key].(int)
}

var data = make(GenericMap)

type Foo struct {
	Name string
}

func main() {
	data["foo"] = &Foo{"John"}

	foo := data.GetFoo("foo")

	fmt.Println(foo.Name)
}

You might want to add error checking, in case the key does not exists or is not the expected type.

huangapple
  • 本文由 发表于 2014年9月22日 23:24:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/25977731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定