英文:
golang reflect create object is error
问题
less main.go
输出:
package main
import (
"reflect"
"net/url"
"fmt"
)
type User struct {
Id uint64 `json:"id"`
No *string `json:"no"`
Identity string `json:"identity"`
Head url.URL `json:"head"`
}
func main() {
t := reflect.TypeOf(User{})
u := reflect.New(t).Elem().Interface()
fmt.Printf("u is %T, %v\n", u, u)
}
go version
输出:
go version go1.5.2 darwin/amd64
go build main.go
正确
./main
输出:
u is main.User, {0 <nil> { <nil> }}
怎么回事?为什么 u 对象只有第三个字段?User 结构体包含四个字段!
在我的真实项目中,我发现创建的对象的字段类型不正确。
英文:
less main.go
output:
package main
import (
"reflect"
"net/url"
"fmt"
)
type User struct {
Id uint64 `json:"id"`
No *string `json:"no"`
Identity string `json:"identity"`
Head url.URL `json:"head"`
}
func main() {
t := reflect.TypeOf(User{})
u := reflect.New(t).Elem().Interface()
fmt.Printf("u is %T, %v\n", u, u)
}
go version
output:
go version go1.5.2 darwin/amd64
go build main.go
correct
./main
output:
u is main.User, {0 <nil> { <nil> }}
what the matter?? why u object only third field? the User struct include four field!
In my really project, I find the created object's field's type is incorrect
答案1
得分: 0
你的结构实际上有4个字段,注意额外的空格来分隔空字符串字段。
尝试使用%#v
来显示你的结构的golang语法表示,这样更容易阅读(但在大型结构上可能会变得非常拥挤)。
英文:
Your structure actually have 4 fields, notice the extra whitespaces that delimit the empty string field.
Try using the %#v
to show the golang-syntax representation of your struct, that's much more easier to read (but can become quite crowded on big structures).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论