dongxi5423 2015-03-01 11:15
浏览 47
已采纳

生成:字符串:无效的操作:没有字段或方法字符串

I'm trying to use the stringer cmd so that I can generate String() methods for some int types. Here is how the code looks like

//go:generate stringer -type=MyIntType
type MyIntType int

const (
    resource MyIntType = iota
)
func myfunc(){
print(resource.String())
}

The error I'm getting on go generate command is invalid operation: resource (constant 0 of type MyIntType) has no field or method String which makes sense because there is no String method yet. How am I supposed to fix this error if stringer cmd is supposed to actually generate the String method? Should I use fmt.Sprintf("%s", resource) all over the code ? it looks a bit ugly to me. At least not as nice as resource.String().

  • 写回答

2条回答 默认 最新

  • doujian3132 2015-03-01 20:27
    关注

    Each file must be parsed and type checked by the types library before the methods are generated. This usually doesn't pose a problem, since the String() method is rarely called directly, and is used by passing a value to something like fmt.Println that always checks first for a Stringer.

    You can either not call String() yourself:

    file: type.go

    //go:generate stringer -type=MyIntType
    package painkiller
    
    import "fmt"
    
    type MyIntType int
    
    const (
        resource MyIntType = iota
    )
    
    func myfunc() {
        fmt.Println(resource)
    }
    

    Or you can put the calls in another file, and pass only the files that stringer needs as arguments. With no arguments, stringer checks the package as a whole, but if you provide only a list of files, they assume that some methods may be defined in files not provided.

    file: type.go

    //go:generate stringer -type=MyIntType type.go
    package foo
    
    type MyIntType int
    
    const (
        resource MyIntType = iota
    )
    

    file myfunc.go

    package foo
    
    func myfunc() {
        print(resource.String())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?