3

I'm somewhat new to Golang but very new to 1.18 generics.

I have two compile-time errors in the following program and can't figure out how to get it working.

Any help would be greatly appreciated.

package main

import (
    "database/sql"
)

type SeriesType interface {
    sql.NullTime | sql.NullInt64 | sql.NullFloat64 | sql.NullString
}

type Series[T SeriesType] struct {
    Name   string
    Values []T
}

func NewSeries[T SeriesType](name string) Series[T] {
    s := Series[T]{Name: name, Values: make([]T, 0)}
    return s
}

func (s *Series[T]) Append(e any) error {
    var t T   //T = sql.NullInt64 so t is a struct of type sql.NullInt64
    t.Scan(e) //***** compile error: t.Scan undefined (type T has no field or method Scan)
    s.Values = append(s.Values)
    return nil
}

func (s *Series[T]) Print() {
    for i := range s.Values {
        println(s.Values[i].Int64) //**** compile error: s.Values[i].Int64 undefined (type T has no field or method Int64)
    }
}

func main() {
    s := NewSeries[sql.NullInt64]("test")
    s.Name = "newTest"
    println(s.Name) //prints "newTest"
    s.Append(1)
    s.Print()
}
vocalionecho
  • 301
  • 4
  • 9
  • notice the signature of the receiver on the appropriate method https://pkg.go.dev/database/sql#NullInt64.Scan se also the method set def https://go.dev/ref/spec#Method_sets –  May 28 '22 at 21:02

0 Answers0