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条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装