package pizza
import (
"fmt"
"strings"
)
type Topping int32
const (
CHEESE Topping = iota
PEPPERONI
MUSHROOMS
)
func (t Topping) String() string {
switch {
case t == CHEESE:
return "Cheese"
case t == PEPPERONI:
return "Pepperoni"
case t == MUSHROOMS:
return "Mushrooms"
}
return "?"
}
type Pizza struct {
size int32
toppings []Topping
}
func (p *Pizza) String() string {
return strings.Join(p.toppings, ",")
}
func main() {
p := &Pizza{14, []Topping{CHEESE, PEPPERONI}}
fmt.Println(p)
}
- Robert
On Jun 14, 2011, at 10:36 PM, Robert Snedegar <vik...@gmail.com> wrote:
> If I have a type that has a String(), and I want to pass a slice of it
> to strings.Join for easy printing, is there a way to convert it to be
> a []string, or do I need to write my own copy of Join?
Easiest way to turn a []Toppings into a []string is just to use a loop:
strs := make([]string, len(p.toppings))
for i, v := range p.toppings {
strs[i] = v.String()
}
return strings.Join(strs, ", ")
Maybe create an interface StringJoinable whose only method is String()
and by implementing String for any type, they can be passed to
strings.SuperJoin([]StringJoinable)?
Even if Topping implements a Stringer interface, a []Topping won't be
a []Stringer, as they have different memory layouts. For more
background, read:
http://research.swtch.com/2009/11/go-data-structures.html
http://research.swtch.com/2009/12/go-data-structures-interfaces.html
In your case, I think that the thing to do is to write your own copy
of Join, whether as a standalone function or as a method on a
[]Topping type.