How can I get the string representation of a struct?

前端 未结 5 822
闹比i
闹比i 2021-01-30 16:04

For my application, it does not matter if the string is human readable or not.

5条回答
  •  旧巷少年郎
    2021-01-30 16:23

    you can also add a function with that struct receiver.

    // URL : Sitemap Xml
    type URL struct {
        Loc string `xml:"loc"`
    }
    
    // URLSET : Sitemap XML
    type URLSET struct {
        URLS []URL `xml:"url"`
    }
    
    // converting the struct to String format. 
    func (u URL) String() string {
        return fmt.Sprintf(u.Loc)
    }
    

    So printing this struct field will return a string.

    fmt.Println(urls.URLS)
    

提交回复
热议问题