简体   繁体   中英

golang reflect create object is error

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM