登录
首页 >  Golang >  Go问答

接口包含类型约束:不能在转换中使用接口

来源:stackoverflow

时间:2024-04-18 10:57:36 452浏览 收藏

从现在开始,努力学习吧!本文《接口包含类型约束:不能在转换中使用接口》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

type Number interface {
    int | int64 | float64
}

type NNumber interface {
}

//interface contains type constraints
//type NumberSlice []Number

type NNumberSlice []NNumber

func main() {
    var b interface{}
    b = interface{}(1)
    fmt.Println(b)

    // interface contains type constraints
    // cannot use interface Number in conversion (contains specific type constraints or is comparable)
    //a := []Number{Number(1), Number(2), Number(3), Number(4)}
    //fmt.Println(a)

    aa := []interface{}{interface{}(1), interface{}(2), interface{}(3), 4}
    fmt.Println(aa)

    aaa := []NNumber{NNumber(1), NNumber(2), NNumber(3), 4}
    fmt.Println(aaa)
}

为什么 number 切片 a 无法这样初始化?

numberslicennumberslice 看起来很相似,但是什么意思类型约束,看起来语法很奇怪


正确答案


语言规范明确禁止使用带有类型元素的接口作为类型参数约束之外的任何内容(引用位于第 Interface types 段下):

basic 的接口只能用作类型约束,或用作用作约束的其他接口的元素。它们不能是值或变量的类型,也不能是其他非接口类型的组件。

嵌入 comparable 或其他非基本接口的接口也是非基本接口。您的 number 接口包含一个联合,因此它也是非基本的。

一些例子:

// basic: only methods
type a1 interface {
    getname() string
}

// basic: only methods and/or embeds basic interface
type b1 interface {
    a1
    setvalue(v int)
}

// non-basic: embeds comparable
type message interface {
    comparable
    content() string
}

// non-basic: has a type element (union)
type number interface {
    int | int64 | float64
}

// non-basic: embeds a non-basic interface
type specialnumber interface {
    number
    isspecial() bool
}

在变量 a 的初始化中,您尝试在类型转换 number(1) 中使用 number,这是不允许的。

您只能使用 number 作为类型参数约束,即限制泛型类型或函数实例化所允许的类型。例如:

type Coordinates[T Number] struct {
    x, y T
}

func sum[T Number](a, b T) T {
    return a + b
}

好了,本文到此结束,带大家了解了《接口包含类型约束:不能在转换中使用接口》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>