获取没有指针的结构标签

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

Get struct tag without pointer

问题

我正在为Go语言中的固定宽度文本创建一个简单的编组器,详细信息请参见这里

编组器现在按照我的预期工作,尽管还缺少一些功能。我在编组函数中遇到的问题是:

相关的代码如下:

func Marshal(obj interface{}) (str string, err error) {
    ...
    elemsType := reflect.TypeOf(obj).Elem()

正如你所看到的,我试图模仿json包的编组函数签名。问题在于,当我尝试将值传递给编组函数时,reflect.TypeOf返回的类型与我传递给它的类型不同。只有当我将指针传递给编组函数时,该函数才能执行。

这样可以工作:

user := User{"johnjohnjohn", "the", "doe", "smart", 26}
res, err := Marshal(&user)

这样不行:

user := User{"johnjohnjohn", "the", "doe", "smart", 26}
res, err := Marshal(user)

有没有办法只传递值,然后在编组函数内部获取结构体标签呢?

英文:

I was creating a simple marshaler for fixed with text into struct in Go, as detailed here.

The marshaler functions as I expected now, albeit still lacking some features. What I got stuck in is in the marshal function.

The relevant code is as follow

func Marshal(obj interface{}) (str string, err error) {
...
	elemsType := reflect.TypeOf(obj).Elem()

As you can see, I tried to mimic the json package's marshal signature. Then only problem is when I tried to pass by value to the marshal function, the reflect.TypeOf returns a different type than the one I pass into it. The function can only executed if I'm passing pointer to the marshal function.

This works

user := User{"johnjohnjohn", "the", "doe", "smart", 26}
res, err := Marshal(&user)

This doesn't

user := User{"johnjohnjohn", "the", "doe", "smart", 26}
res, err := Marshal(user)

Is there any way to just pass by value, and then get the struct tag inside the marshal function?

答案1

得分: 6

如果你希望它适用于值,就不要在反射类型上调用Type.Elem()。为了处理指针和非指针类型,可以先检查是否为指针类型,然后再调用Type.Elem()

elemsType := reflect.TypeOf(obj)
if elemsType.Kind() == reflect.Ptr {
    elemsType = elemsType.Elem()
}
英文:

If you want it to work on values, don't call Type.Elem() on the reflect type. To handle both (pointers and non-pointers), check if it is of pointer type, and only then call Type.Elem():

elemsType := reflect.TypeOf(obj)
if elemsType.Kind() == reflect.Ptr {
    elemsType = elemsType.Elem()
}

huangapple
  • 本文由 发表于 2017年7月25日 20:12:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/45302935.html
匿名

发表评论

匿名网友

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

确定