fork download
  1. // Playground for https://stackoverflow.com/a/56699658/11458991
  2.  
  3. package main
  4.  
  5. import (
  6. "fmt"
  7. "errors"
  8. "log"
  9. "reflect"
  10. "strings"
  11. )
  12.  
  13. // RowID stores the ID of a single row in a table. An ID can be a composite of multiple columns
  14. type RowID []string
  15.  
  16. // String implements Stringer interface for RowID
  17. func (r RowID) String() string {
  18. return fmt.Sprintf("[%s]", strings.Join(r, ", "))
  19. }
  20.  
  21. func castToStringerSlice(iface interface{}) ([]fmt.Stringer, bool /* ok */) {
  22. if reflect.TypeOf(iface).Kind() != reflect.Slice {
  23. return nil, false
  24. }
  25.  
  26. v := reflect.ValueOf(iface)
  27. stringers := make([]fmt.Stringer, v.Len())
  28.  
  29. for i := 0; i < v.Len(); i++ {
  30. stringers[i] = v.Index(i)
  31. }
  32.  
  33. return stringers, true
  34. }
  35.  
  36. func PrintChanges(iface_ids interface{}) {
  37. ids, ok := castToStringerSlice(iface_ids)
  38. if !ok {
  39. log.Fatal(errors.New("the argument to PrintChanges must be a slice of Stringers"))
  40. }
  41. for _, id := range ids {
  42. fmt.Println(id)
  43. }
  44. }
  45.  
  46. func PrintChange(id fmt.Stringer) {
  47. fmt.Println(id)
  48. }
  49.  
  50. func main() {
  51. rowIDs := []RowID{
  52. {"1", "2"},
  53. {"22"},
  54. }
  55.  
  56. PrintChange(rowIDs[0])
  57.  
  58. PrintChanges(rowIDs)
  59. }
Success #stdin #stdout 0s 3144KB
stdin
Standard input is empty
stdout
[1, 2]
[1 2]
[22]