我正在测试go 1.18中的仿制药,并查看了这example个.

这是我在迭代切片时遇到的一些问题.这就是我try 的:


import "fmt"

// NumberSlice constraint
type NumberSlice interface {
    []int64 | []float64
}

func add[N NumberSlice](n N) {
    // want: to range over n and print value of v

    // got: cannot range over n (variable of type N constrained by NumberSlice)
    // (N has no core type)
    for _, v := range n {
        fmt.Println(v)
    }
}

func main() {
    ints := []int64{1, 2}
    add(ints)
}

我如何做到这一点?

推荐答案

接口(包括接口约束)的core type定义如下:

如果满足以下条件之一,则接口T具有核心类型:

  • a single type 100 which is the underlying type of all types in the type set of T

  • 或者T的类型集只包含具有相同元素类型E的通道类型,并且所有定向通props 有相同的方向.

接口约束没有核心类型,因为它有two个底层类型:[]int64[]float64.

因此,不能在需要核心类型的地方使用它.尤其是rangemake.

您可以更改接口以要求基类型,然后在函数签名中指定切片:

// still no core type...
type Number interface {
    int64 | float64
}

// ...but the argument will be instantiated with either int64 or float64
func add[N Number](n []N) {
    for _, v := range n {
        fmt.Println(v)
    }
}

这也有效,但要详细得多:

type NumberSlice[N int64 | float64] interface {
    // one core type []N
    ~[]N
}

func add[S NumberSlice[N], N int64 | float64](n S) {
    for _, v := range n {
        fmt.Println(v)
    }
}

Go相关问答推荐

Go程序在并发Forking 循环中停留在syscall.Wait4

golang.org/x/oauth2 oauth2.Config.Endpoint.TokenURL mock:缺少access_token

如何使用 go 读取 RDF xml 文件中的 XML 命名空间属性

Go 1.20 中如何计算连接错误?

日志(log)文件不在 golang 的日志(log)目录中

当我有外键时,如何使用 GORM 创建数据库的新条目

Golang Gorm Fiber - 如何将定义为别名的名称发送到索引模板?

切片的下限和上限

用接口来模拟amqp091go的困难

使用反射在Go中递归迭代 struct 体和集合字段

你如何在 Golang 代码中测试 filepath.Abs​​ 失败?

如何在模板中传递和访问 struct 片段和 struct

如何使用 Go 代理状态为 OK 的预检请求?

Golang:如何判断通过缓冲通道进行通信时生产者或消费者是否较慢?

没有堆栈跟踪的 go 程序崩溃是什么意思?

Go AST:获取所有 struct

golang 如何从字符串中查找表情符号?

Go lang - 惯用的默认后备

HTTP 重定向不呈现新页面

为什么 Go 中的 maps.Keys() 将 map 类型指定为 M?