我有一个定义如下的结构
type WallpaperType int
// ...
type WallpaperInfo struct {
WallpaperType WallpaperType `json:"type"`
HelpMsg string `json:"help"`
Path string `json:"path"`
ImageColor color.RGBA `json:"imageColor"`
}
使用打印这样的结构
winfo := &WallpaperInfo{...}
log.Println(winfo)
log.Printf("%+v\n", winfo)
给出这样的东西
&{Slideshow Wallpaper is a slideshow D:\Images\Wallpapers\autumn-autumn-leaves-blur-close-up-589840.jpg {219 77 66 167}}
&{WallpaperType:Slideshow HelpMsg:Wallpaper is a slideshow Path:D:\Images\Wallpapers\autumn-autumn-leaves-blur-close-up-589840.jpg ImageColor:{R:219 G:77 B:66 A:167}}
我想将它打印为 JSON,所以我实现String了结构的方法如下
func (w WallpaperInfo) String() string {
bytes, err := json.Marshal(w)
if err != nil {
return "" // ???
// this will call the method recursively
// return fmt.Sprintf("%+v\n", w)
}
return string(bytes)
}
万一String()方法有误,
我想打印原件&{WallpaperType:Slideshow HelpMsg:Wallpaper is a slideshow Path:D:\Images\Wallpapers\autumn-autumn-leaves-blur-close-up-589840.jpg ImageColor:{R:219 G:77 B:66 A:167}}
我试过返回fmt.Sprintf("%+v\n", w),但它会递归调用同一个函数。
有什么办法可以返回原始结构格式?因为如果 json 失败,我不知道如何以不同的方式打印它。