I want to write a Join
function that takes arbitrary objects with a String()
method:
package main
import (
"fmt"
"strings"
)
type myint int
func (i myint) String() string {
return fmt.Sprintf("%d", i)
}
func main() {
parts := []myint{myint(1), myint(5), myint(6)}
fmt.Println(Join(parts, ", "))
}
func Join(parts []fmt.Stringer, sep string) string {
stringParts := make([]string, len(parts))
for i, part := range(parts) {
stringParts [i] = part.String()
}
return strings.Join(stringParts , sep)
}
http://play.golang.org/p/EhkbyibzHw
[]myint
cannot be passed to Join
, because it is not of type fmt.Stringer
, so I have to write:
parts := []fmt.Stringer{myint(1), myint(5), myint(6)}
But what if I need parts
for another operation where the values have to be ints? Should I cast a slice of myint
to a slice of Stringer
then?