简体   繁体   中英

missing type in composite literal in nested struct

I have the following anonymous struct:

func wrapHal(selfHref string) interface{} {
    return struct {
        _links struct {
            self struct {
                href string
            }
        }
    }{
        _links: {self: {href: selfHref}}, # this line
    }
}

However, in "this line, " I get the error missing type in composite literal

How to fix it? It is possible to initiate a anonymous nested struct in Go?

To initialize an anonymous struct, you have to declare the type. You declared the root anonymous struct, but you need to do again for each nested anonymous struct:

func wrapHal(selfHref string) interface{} {
    return struct {
        _links struct {
            self struct {
                href string
            }
        }
    }{
        _links: struct {
            self struct {
                href string
            }
        }{
            self: struct {
                href string
            }{
                href: "",
            },
        },
    }
}

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