我有一个关于 Go 中自定义类型的问题。我正在尝试使用 any
获得某种类型安全性。我从 TypeScript 知道联合类型,但据我所知,联合类型在 Go 中是不可能的。什么是可行的替代方案?
我希望函数或字段的类型为 any
,因为我事先不知道类型。但我也想限制可能的类型,以便编译器提示意外的类型。
据我所知,这确实适用于常规自定义类型,例如 type x string
等,但不适用于 struct
。
这是一个配置示例:
package main
import "fmt"
type plantConfig any
type treeConfig struct {
trunkDiameter float64
}
func newTreeConfig(config treeConfig) plantConfig {
return config
}
type flowerConfig struct {
color string
}
func newFlowerConfig(config flowerConfig) plantConfig {
return config
}
// newGarden should only take plantConfig.
func newGarden(config plantConfig) {
switch config.(type) {
case treeConfig:
fmt.Println("planted trees")
case flowerConfig:
fmt.Println("planted flowers")
default:
fmt.Println("unknown plant")
}
}
// waterfallConfig is NOT a plantConfig. newGarden should not accept this as
// parameter.
type waterfallConfig struct {
height float64
}
func main() {
// This does not report any errors while compiling.
newGarden(waterfallConfig{})
}
输出:
unknown plant
但是,我希望编译器会提示 newGarden(waterfallConfig{})
因为 waterfallConfig
不是 plantConfig
类型,而且它不应隐式强制转换。
当然,我可以使 plantConfig
成为一个具有相当“独特”的方法名称的接口(interface),但这对我来说似乎并不干净。有什么建议么?或者我错过了一些明显的东西?
最佳答案
您的方向是正确的,但您需要一个限制您可以使用的类型的接口(interface)类型,而不是任何(interface{})。因此,像这样声明 plantConfig:
type plantConfig interface{ ImplementsPlant() }
然后你只需要说允许的类型实现该接口(interface),如下所示:
func (treeConfig) ImplementsPlant() {}
func (flowerConfig) ImplementsPlant() {}
关于go - Go 结构的自定义类型强制执行(类型为任意),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76584992/