Created
October 28, 2015 09:47
-
-
Save tucnak/aa5c41a638c32948303f to your computer and use it in GitHub Desktop.
First-class support of interface slices!
This file contains 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 | |
import ( | |
"fmt" | |
"strconv" | |
) | |
type FancyInt int | |
func (x FancyInt) String() string { | |
return strconv.Itoa(int(x)) | |
} | |
type FancyRune rune | |
func (x FancyRune) String() string { | |
return string(x) | |
} | |
// Literally any object with String() method | |
type Stringy interface { | |
String() string | |
} | |
// String, made of string representations of items given. | |
func Join(items []Stringy) (joined string) { | |
for _, item := range items { | |
joined += item.String() | |
} | |
return | |
} | |
func main() { | |
numbers := []FancyInt{1, 2, 3, 4, 5} | |
runes := []FancyRune{'a', 'b', 'c'} | |
// You can't do this! | |
// | |
// fmt.Println(Join(numbers)) | |
// fmt.Println(Join(runes)) | |
// | |
// prog.go:40: cannot use numbers (type []FancyInt) as type []Stringy in argument to Join | |
// prog.go:41: cannot use runes (type []FancyRune) as type []Stringy in argument to Join | |
// | |
// Instead, you are supposed to do this: | |
// | |
properNumbers := make([]Stringy, len(numbers)) | |
for i, number := range numbers { | |
properNumbers[i] = number | |
} | |
properRunes := make([]Stringy, len(runes)) | |
for i, r := range runes { | |
properRunes[i] = r | |
} | |
fmt.Println(Join(properNumbers)) | |
fmt.Println(Join(properRunes)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment