创建对象时出现错误的反射。

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

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 (
        &quot;reflect&quot;
        &quot;net/url&quot;
        &quot;fmt&quot;
    )
    
    type User struct {
        Id uint64 `json:&quot;id&quot;`
        No *string `json:&quot;no&quot;`
        Identity string `json:&quot;identity&quot;`
        Head url.URL `json:&quot;head&quot;`
    }
    
    func main() {
        t := reflect.TypeOf(User{})
        u := reflect.New(t).Elem().Interface()
        fmt.Printf(&quot;u is %T, %v\n&quot;, u, u)
    }

go version output:

go version go1.5.2 darwin/amd64

go build main.go correct

./main output:

u is main.User, {0 &lt;nil&gt;  {  &lt;nil&gt;     }}

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).

huangapple
  • 本文由 发表于 2015年12月23日 23:14:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/34438636.html
匿名

发表评论

匿名网友

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

确定