Skip to content

Instantly share code, notes, and snippets.

@ewalk153
Created July 6, 2012 14:07
Show Gist options
  • Save ewalk153/3060345 to your computer and use it in GitHub Desktop.
Save ewalk153/3060345 to your computer and use it in GitHub Desktop.
Change from []Struct to []Interface in go
package main
type Box interface {
Width() int
}
type Square struct {
w int
}
func (sq Square) Width() int {
return sq.w
}
func GraphGen() []Square {
sqs := make([]Square, 5)
for i:=0; i<5; i++ {
sqs[i] = Square{i}
}
return sqs
}
/*
Would like to be able to pass an array []Square in here
*/
func PrintBoxes(sqs []Box) {
for i:=0; i< len(sqs); i++ {
PrintBox(sqs[i])
}
}
func PrintBox(sq Box) {
println(sq.Width())
}
func main() {
sqs := GraphGen()
bxs := make([]Box, len(sqs))
copy(sqs[:], bxs[:])
for bx := range bxs {
println(bx)
}
//PrintBoxes(sqs) // fails to compile because []Box is not the same as []Square
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment