在struct标签中使用fmt说明符



是否可以在Golang的struct标签中使用fmt说明符或类似的东西,例如

type MyReqest struct {
category string fmt.Sprintf(`json:"category" binding:"required,oneof=%s"`, strings.Join(options, " "))
}

这是不工作,但我想知道是否Golang支持这样的功能。

不,这不可能。最接近的可能是使用go generate代码生成器来生成包括标签在内的整个结构体。这将在构建时完成,而不是运行时。

参见:https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source和https://go.dev/blog/generate。

如果你需要在运行时这样做,你可以使用reflect.StructOf在运行时用标签定义整个结构体。

最新更新