go - go 支持多类型吗? (泛型类型)

标签 go types interface

type MyNumber interface {
    float32, float64, uint, int // this is not supported
}

func PrintNumber(n MyNumber) {
    switch n.(type) {
    case float32, float64, uint, int:
        fmt.Printf("%v\n", n)
    default:
        panic("PrintNumber only supports types float32, float64, uint, int")
    }
}

在go中,可以定义一个空白接口(interface),基本上允许任何类型
var v interface{}
v = "string"
v = 0.1

有没有办法将允许的类型减少到特定的类型列表?

就像是
type MyNumber float32, float64, uint, int

或者
type MyNumber interface {
    float32, float64, uint, int
}

这样我就可以让编译器检查函数是否支持该类型。

最佳答案

Is there a way to reduce the allowed types to a specific list of types [of an empty interface]?



在编译时,没有。

但是,您可以选择在运行时使用限制。当有其他选择时,应该避免这种情况,因为它不能提供足够的安全性。

这是在标准库中的许多地方完成的,例如 json marshaler,它需要一个指针作为目标。

关于go - go 支持多类型吗? (泛型类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60912573/

相关文章:

c# - 通过 C# 中的反射获取 'basic' 数据类型而不是奇怪的可空数据类型

java - 将接口(interface)嵌套在具体类中的可行设计替代方案是什么?

google-app-engine - 使用 Go 的 App Engine 上的静态文件托管限制

go - 什么会导致 malloc 忽略交换空间?

python - 元类可以调用吗?

c# - 类型 'MyClass' 无法从未标记为 DataContractAttribute 或 SerializableAttribute 的类型继承。考虑标记基本类型

C++:什么是类接口(interface)?

sorting - Go 中的内联函数

go - 如何在 Golang 中使用 goroutines 读取标准输入?

java - Kotlin 传入实现参数化接口(interface)的类型