go - Go 结构的自定义类型强制执行(类型为任意)

标签 go type-conversion

我有一个关于 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/

相关文章:

go - go lang 中 map 的序列化和反序列化问题

java - 如何将数字的二进制表示形式的java链表转换为数字的十进制表示形式的字符串?

java - 如何组合三个连续的Modbus寄存器以获得整数值?

PHP 将 KB MB GB TB 等转换为字节

go - 如何从嵌套函数修改 struct boolean?

json - 如何使原始 unicode 编码的内容可读?

go - 类型转换和类型断言有什么区别?

javascript - 从 ISO 日期转换为良好的格式化字符串

arrays - 按值对 map 排序,然后将其放入GO中的另一张 map 中

stream - 如何在 Go 中读取至少 N 个字节