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

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?