Analogous to
type IntSlice []int
func (p IntSlice) Len() int { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i].val < p[j].val }
func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
and then calling sort.Sort() on an IntSlice, I figured I
could create a type that is a new name for an instantiated generic type and
then call methods on that new type... but no?
For example:
https://go.dev/play/p/K5FGtNi6hLM
package main
import "fmt"
type Addable interface {
~complex128 | ~complex64 | ~float64 | ~float32 |
~byte | ~uint16 | ~uint32 | ~uint64 |
~int8 | ~int16 | ~int32 | ~int64 | ~int
}
type Matrix[T Addable] struct {
Nrow int
Ncol int
Dat []T
}
func (m *Matrix[T]) Col(j int) (res []T) {
for i := 0; i < m.Nrow; i++ {
res = append(res, m.At(i, j))
}
return
}
// At reads out the [i,j]-th element.
func (m *Matrix[T]) At(i, j int) T {
return m.Dat[i*m.Ncol+j]
}
func main() {
m := &Matrix[float64]{
Nrow: 2,
Ncol: 3,
Dat: make([]float64, 2*3),
}
fmt.Printf("m.At(1,2) = '%v'", m.At(1, 2)) // this is fine, of course.
}
// I assumed this would work... but go 1.21 rejects the call to At() below.
type MatrixF64 Matrix[float64]
func UseMatrixF64(m *MatrixF64) {
// so why won't this compile? if the same line in main() works?
fmt.Printf("m.At(1,2) = '%v'", m.At(1, 2)) // compile error: m.At undefined
(type *MatrixF64 has no field or method At)
}
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/6372578a-3e57-4dfe-a0f9-272ddbcaa2e9n%40googlegroups.com.