英文:
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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论