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

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().

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())
}

The stringer cmd calls the go/parser.ParseFile for every go file. Thus if you have a method that is not declared it will fail. You will have to use fmt.Sprint* statements to get over this. Or you could tell go generate to only generate a specific file.

I don't know if we could term this as a bug. You could file it, probably see what the response is.