gpt4 book ai didi

去生成 : stringer: invalid operation: has no field or method String

转载 作者:IT王子 更新时间:2023-10-29 01:48:15 26 4
gpt4 key购买 nike

我正在尝试使用 stringer cmd 以便我可以为某些 int 类型生成 String() 方法。这是代码的样子

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

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

我在执行 go generate 命令时遇到的错误是 invalid operation: resource (constant 0 of type MyIntType) has no field or method String 这是有道理的,因为还没有 String 方法。如果 stringer cmd 应该实际生成 String 方法,我应该如何修复此错误?我应该在整个代码中使用 fmt.Sprintf("%s", resource) 吗?我觉得有点难看。至少不如 resource.String() 好。

最佳答案

每个文件都必须由 types 进行解析和类型检查生成方法之前的库。这通常不会造成问题,因为 String() 方法很少被直接调用,而是通过将值传递给总是检查的 fmt.Println 来使用首先是 Stringer

您可以自己调用String():

文件:type.go

//go:generate stringer -type=MyIntType
package painkiller

import "fmt"

type MyIntType int

const (
resource MyIntType = iota
)

func myfunc() {
fmt.Println(resource)
}

或者您可以将调用放在另一个文件中,并只传递 stringer 需要的文件作为参数。在没有参数的情况下,stringer 会检查整个包,但如果您只提供文件列表,他们会假设某些方法可能在未提供的文件中定义。

文件:type.go

//go:generate stringer -type=MyIntType type.go
package foo

type MyIntType int

const (
resource MyIntType = iota
)

文件 myfunc.go

package foo

func myfunc() {
print(resource.String())
}

关于去生成 : stringer: invalid operation: has no field or method String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com