On Friday, 21 September 2012 15:44:57 UTC+2, Robert Carlsen wrote:
A type switch could be helpful too.
Thanks, no more reflect. :D funny because the video is promoting the reflect capabilities but Russ also says one should avoid it if possible.
Final (How to choose the interface to use an interface{} as):
package main
import (
"os"
"strconv"
)
type something struct {
woot string
}
func (s something) String() string {
return "used something.String()" + s.woot
}
func main() {
myprint2("Hello", 42, something{"wowee"}, "\n")
}
func myprint2(args ...interface{}) {
for _, arg := range args {
if _, ok := arg.(Stringer); ok {
os.Stdout.WriteString(arg.(Stringer).String())
continue
}
switch arg.(type) {
case int:
os.Stdout.WriteString(strconv.FormatInt(int64(arg.(int)), 10))
case string:
os.Stdout.WriteString(arg.(string))
default:
panic("Unhandled type")
}
}
}
type Stringer interface {
String() string
}
Just for searching later; error was:
./myprint.go:36: cannot use arg (type interface {}) as type Stringer in function argument:
interface {} does not implement Stringer (missing String method)