dtn36013 2018-08-16 23:26
浏览 90

纠正有关格式错误参数的“ go vet”警告

I have a struct that contains a pointer to another struct. That is,

type InnerStruct struct {
    whatever bool
}

type OuterStruct struct {
    is *InnerStruct
}

If I print out an instance of OuterStruct with %+v, then the inner struct is not expanded like it would be if it weren't a pointer. I understand and accept why that is, but because I don't have any chance of recursion, I'd like to get the full thing printed out.

It occurred to me that I might be able to implement the Formatter interface on a pointer receiver of InnerStruct in order to get the behavior I want, and indeed, the following does exactly what I want, at least for the cases I had (perhaps there are ways in which it could go horribly wrong; please tell me!):

func (is *InnerStruct) Format(s fmt.State, verb rune) {
    switch verb {
    case 'v':
        if s.Flag('+') {
            fmt.Fprintf(s, "&%+v", *is)
        } else if s.Flag('#') {
            fmt.Fprintf(s, "&%#v", *is)
        } else {
            fmt.Fprintf(s, "&%v", *is)
        }
    case 's':
        fmt.Fprintf(s, "&%s", *is)
    }
}

But when I run go vet on the code, it complains:

./thing.go:341: Fprintf format %s has arg *s of wrong type thing.InnerStruct

Is there a better way to get at the default string representation of a struct that avoids this issue with vet?

FWIW, I tried go-spew, and got (almost) the exact output I wanted, so I'll probably just go down that route, but I'd still like to know what, if anything, could be done to satisfy vet.

  • 写回答

1条回答 默认 最新

  • duanpin5168 2018-08-17 00:24
    关注

    You have duplicate names s *InnerStruct and s fmt.State. go vet complains, that you have format verb s instead of v: fmt.Fprintf(s, "&%s", *s).

    Fix your typos. For example,

    package main
    
    import (
        "fmt"
    )
    
    type InnerStruct struct {
        whatever bool
    }
    
    type OuterStruct struct {
        is *InnerStruct
    }
    
    func (s *InnerStruct) Format(f fmt.State, verb rune) {
        switch verb {
        case 'v':
            if f.Flag('+') {
                fmt.Fprintf(f, "&%+v", *s)
            } else if f.Flag('#') {
                fmt.Fprintf(f, "&%#v", *s)
            } else {
                fmt.Fprintf(f, "&%v", *s)
            }
        case 's':
            fmt.Fprintf(f, "&%v", *s)
        }
    }
    
    func main() {}
    

    Playground: https://play.golang.org/p/B2pAus3kEwt

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题