【发布时间】:2022-11-10 03:38:14
【问题描述】:
我想让下面的代码编译。我从阅读 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: v.A 未定义(类型 T 没有字段或方法 A)我希望
T代表具有特定类型的特定字段的所有结构。添加~没有帮助。这是提案中的一个示例,该示例已实施并且是最新的 Go beta 版本的一部分。
type structField interface { struct { a int; x int } | struct { b int; x float64 } | struct { c int; x uint64 } }
【问题讨论】:
-
目前不支持字段访问:github.com/golang/go/issues/48522#issuecomment-924380147(它可能在 Go 1.19 中添加)