Created
July 6, 2012 14:07
-
-
Save ewalk153/3060345 to your computer and use it in GitHub Desktop.
Change from []Struct to []Interface in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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