Created
May 5, 2022 08:22
-
-
Save takekazuomi/60e71f48441fc0ab155be2b7c68064c2 to your computer and use it in GitHub Desktop.
constraint struct fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
type common struct { | |
ID string | |
Created time.Time | |
} | |
type entity[T any] struct { | |
common | |
data T | |
} | |
type userEntity struct { | |
common | |
FirstName string | |
LastName string | |
} | |
type otherEntity struct { | |
common | |
FirstName string | |
LastName string | |
} | |
type Vector[T constraint] []T | |
type constraint interface { | |
common | userEntity | |
} | |
func (v *Vector[T]) PrintID() { | |
e := (*v)[0] | |
fmt.Printf("hello %v", e.ID) | |
} | |
func main() { | |
// var v = Vector[otherEntity]{} | |
var v = Vector[userEntity]{} | |
v.PrintID() | |
} |
The Go compiler does not support accessing a struct field x.f where x is of type parameter type even if all types in the type parameter's type set have a field f. We may remove this restriction in a future release.
https://tip.golang.org/doc/go1.18#:~:text=The%20Go%20compiler%20does%20not%20support%20accessing%20a%20struct%20field%20x.f%20where%20x%20is%20of%20type%20parameter%20type%20even%20if%20all%20types%20in%20the%20type%20parameter%27s%20type%20set%20have%20a%20field%20f.%20We%20may%20remove%20this%20restriction%20in%20a%20future%20release.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
maybe here
golang/go#48522