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

interface contains type constraints: cannot use interface in conversion

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 下):

Interfaces that are not basic may only be used as type constraints, or as elements of other interfaces used as constraints. They cannot be the types of values or variables, or components of other, non-interface types.

嵌入 comparable 或另一个 non-basic 接口的接口也是 non-basic。您的 Number 接口包含一个联合,因此它也是 non-basic。

举几个例子:

// 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
}