鸭子在Go上打字 [英] Duck typing in Go
问题描述
我想写一个 Join
函数,它可以用一个 String()
方法取任意对象:
package main
import(
fmt
strings
)
类型myint int
func(i myint)String()string {
return fmt.Sprintf(%d,i)
}
func main(){
parts:= [] myint {myint(1),myint(5),myint(6)}
fmt.Println (parts,,))
}
func Join(parts [] fmt.Stringer,sep string)string {
stringParts:= make([] string,len (parts))
for i,part:= range(parts){
stringParts [i] = part.String()
}
返回strings.Join(stringParts,sep )
}
http://play.golang.org/p/EhkbyibzHw
[] myint
不能传递给加入
,因为它不是类型 fmt.Stringer
,所以我有t o write:
parts:= [] fmt.Stringer {myint(1),myint(5),myint(6) }
但是如果我需要 parts
另一个值必须是整数的操作?我是否应该将 myint
分割成 Stringer
的片段,然后?
问:我应该将
myint
分割成一片Stringer
然后?
在Go-Only转换中没有强制转换。但是,从一个具体的非接口类型切片转换为一个接口类型切片是不可能的,除非在循环中明确地进行。原因是,例如你的情况, 在附注中,您不必写: 这应该是一样的: I want to write a http://play.golang.org/p/EhkbyibzHw But what if I need Q: Should I cast a slice of There are no casts in Go - only conversions. But conversion from a slice of concrete, non interface type to a slice of interface type is not possible, except by doing it explicitly in a loop. The reason is that, as for example in your case, the On a side note, you don't have to write: This should work identically:
这篇关于鸭子在Go上打字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! [] myint
backing数组的内存布局与 [] fmt.Stringer
有。 (相关常见问题解答)
部分:= [] myint {myint(1),myint (5),myint(6)}
部分:= [] myint {1,5,6}
Join
function that takes arbitrary objects with a String()
method: package main
import (
"fmt"
"strings"
)
type myint int
func (i myint) String() string {
return fmt.Sprintf("%d", i)
}
func main() {
parts := []myint{myint(1), myint(5), myint(6)}
fmt.Println(Join(parts, ", "))
}
func Join(parts []fmt.Stringer, sep string) string {
stringParts := make([]string, len(parts))
for i, part := range(parts) {
stringParts [i] = part.String()
}
return strings.Join(stringParts , sep)
}
[]myint
cannot be passed to Join
, because it is not of type fmt.Stringer
, so I have to write: parts := []fmt.Stringer{myint(1), myint(5), myint(6)}
parts
for another operation where the values have to be ints? Should I cast a slice of myint
to a slice of Stringer
then?
myint
to a slice of Stringer
then?[]myint
backing array has a different memory layout than []fmt.Stringer
has. (Related FAQ)parts := []myint{myint(1), myint(5), myint(6)}
parts := []myint{1, 5, 6}