如何组合仅在参数类型上不同的两个函数

So I have this golang function that looks like this:

func addDaysListener(ch <-chan []entity.Day, db *sql.DB) {
    for days := range ch {
        if len(days) == 0 {
            continue
        }

        logger := logrus.WithFields(logrus.Fields{
            "ticker": days[0].Ticker(),
            "count":  len(days),
        })
        if err := update.InsertDays(db, days); err != nil {
            logger.Error(err)
        } else {
            logger.Info("Inserted Days")
        }
    }
}

I also have a function called addMinutesListener() that is identical EXCEPT:

  • It listens on a <-chan []entity.Minute
  • It calls update.InsertMinutes()

Both entity.Day and entity.Minute implement datum.Candle, although the update functions require the specific type. I'd like to write something like this:

func addItemsListener(db *sql.DB, ch <-chan []datum.Candle, insertFunc func(*sql.DB, []datum.Candle) error) {
    for items := range ch {
        if len(items) == 0 {
            continue
        }

        logger := logrus.WithFields(logrus.Fields{
            "ticker": items[0].Ticker(),
            "count":  len(items),
        })
        if err := insertFunc(db, items); err != nil {
            logger.Error(err)
        } else {
            logger.Info("Inserted Days")
        }
    }
}

...Except the function signature for update.InsertDays and update.InsertMinutes both require the specific type, not the generic type, and the channels are set up like that as well. I could potentially change the channels, but I really can't change the insert functions because they do require the correct type as they insert the data into the database and the fields (properties) vary greatly between the two.

I feel like the correct answer to this problem may be something far more sinister, which is why I'm asking you, SO!

I'm sorry for the nondescript title; please feel free to comment if you have better ideas.

use type assertions

func addDaysListener(ch <-chan []datum.Candle , db *sql.DB) {
    for days := range ch {
        if len(days) == 0 {
            continue
        }

        logger := logrus.WithFields(logrus.Fields{
           "ticker": days[0].Ticker(),
           "count":  len(days),
       })

     switch v:=days.(type){
       case  []entity.Day:
            if err := update.InsertDays(db,v); err != nil {
               logger.Error(err)
            } else {
               logger.Info("Inserted Days")
            }
       case  []entity.Minute:
            if err := update.InsertMinutes(db, v); err != nil {
               logger.Error(err)
            } else {
               logger.Info("Inserted Minutes")
            }

      }

   }
  }