我想让下面的代码编译。我从阅读 Type Parameters Proposal (Go Generics) 的理解是这应该可行,但我必须遗漏一些东西。
package main
import "fmt"
func main() {
s := Struct{A: "Hello World!"}
PrintA(s)
}
func PrintA[T Type](v T) {
fmt.Printf("%s\n", v.A)
}
type Type interface {
struct{ A string }
}
type Struct struct {
A string
}
func (s Struct) String() string {
return s.A
}
我得到的错误是:
./prog.go:7:8: Struct 没有实现 Type (可能缺少 ~ for struct{A string} in constraint Type) ./prog.go:11:23: vA undefined (interface Type没有方法A)
我想T用特定类型的特定字段表示所有结构。添加~没有帮助。
这是提案中的一个示例,该示例已实施并且是最新的 Go beta 版本的一部分。
type structField interface {
struct { a int; x int } |
struct { b int; x float64 } |
struct { c int; x uint64 }
}
https://go.dev/play/p/KZh2swZuD2m?v=gotip
梦里花落0921
相关分类