github.com/haraldrudell/parl@v0.4.176/pslices/convert-slice.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package pslices 7 8 import "github.com/haraldrudell/parl/perrors" 9 10 // ConvertSliceToInterface converts a slice of a struct type to a slice of an interface type. 11 // 12 // - T is any type 13 // - G is an interface type that *T implements 14 // 15 // If *T does not implement G: runtime panic 16 func ConvertSliceToInterface[T, G any](structSlice []T) (interfaceSlice []G) { 17 length := len(structSlice) 18 interfaceSlice = make([]G, length) 19 for i := 0; i < length; i++ { 20 valueAny := any(&structSlice[i]) 21 var ok bool 22 if interfaceSlice[i], ok = valueAny.(G); !ok { 23 var t T 24 var g G 25 panic(perrors.ErrorfPF("type assertion failed: %T does not implement %T", t, g)) 26 } 27 } 28 return 29 }