既然类型参数可以在 上使用golang/go:master,我决定尝试一下。看来我遇到了在类型参数提案中找不到的限制。(或者我一定错过了)。
我想编写一个函数,它返回带有接口类型约束的泛型类型值的切片。如果传递的类型是带有指针接收器的实现,我们如何实例化它?
type SetGetter[V any] interface {
Set(V)
Get() V
}
// SetGetterSlice turns a slice of type V into a slice of type T,
// with T.Set() called for each entry in values.
func SetGetterSlice[V any, T SetGetter[V]](values []V) []T {
out := make([]T, len(values))
for i, v := range values {
out[i].Set(v) // panic if T has pointer receiver!
}
return out
}
Run Code Online (Sandbox Code Playgroud)
当使用类型 as调用上述SetGetterSlice()函数时,此代码将在调用时出现混乱。(Go2go游乐场)毫不奇怪,因为基本上代码创建了一个指针切片:*CountTSet(v)nil …
我有一个这样的界面
type A interface {
SomeMethod()
}
Run Code Online (Sandbox Code Playgroud)
我通过结构指针实现了该接口:
type Aimpl struct {}
func (a *Aimpl) SomeMethod() {}
Run Code Online (Sandbox Code Playgroud)
我有一个通用函数,它接受带有 A 参数的函数,如下所示:
func Handler[T A](callback func(result T)) {
// Essentially what I'd like to do is result := &Aimpl{} (or whatever T is)
callback(result)
}
Run Code Online (Sandbox Code Playgroud)
A另外我应该补充一点,我无法修改(它来自图书馆)的定义。我试过这个:
type MyA[T any] interface{
A
*T
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码给了我一个错误:
func Handler[P any, T MyA[P]](callback func(result A)) {
result := new(P)
callback(result) // result does not implement interface. It's a pointer to a type, not a type …Run Code Online (Sandbox Code Playgroud) 这曾经在 go1.18beta1 中工作,但在 go1.18rc1 中不起作用
package main
type A struct{}
func (*A) Hello() {
println("Hello")
}
func Create[M any, PT interface {
Hello()
*M
}](n int) (out []*M) {
for i := 0; i < n; i++ {
v := PT(new(M))
v.Hello()
out = append(out, v)
}
return
}
func main() {
println(Create[A](2))
}
Run Code Online (Sandbox Code Playgroud)
执行会抛出
./prog.go:16:21: cannot use v (variable of type PT constrained by interface{Hello(); *M}) as type *M in argument to append:
PT does not implement *M …Run Code Online (Sandbox Code Playgroud)