DHl*_*aty 10 convention conventions go
从Golang中的切片创建自己的类型是个好主意吗?
例:
type Trip struct {
From string
To string
Length int
}
type Trips []Trip // <-- is this a good idea?
func (trips *Trips) TotalLength() int {
ret := 0
for _, i := range *trips {
ret += i.Length
}
return ret
}
Run Code Online (Sandbox Code Playgroud)
在Golang中以某种方式创建类似于Trips我的示例中的类型吗?或者最好[]Trip在整个项目中使用?有什么优点和缺点?
Ain*_*r-G 11
据我所知,没有惯例.如果你确实需要它,可以创建切片类型.实际上,如果您想要对数据进行排序,这几乎是唯一的方法:创建类型并sort.Interface在其上定义方法.
此外,在您的示例中,不需要采用地址,Trips因为切片已经是一种"胖指针".所以你可以简化你的方法:
func (trips Trips) TotalLength() (tl int) {
for _, l := range trips {
tl += l.Length
}
return tl
}
Run Code Online (Sandbox Code Playgroud)
如果这是你的类型(切片),它就好了.它使您可以轻松访问底层元素(并允许range迭代),同时提供其他方法.
当然,你可能只应该在这种类型上保留必要的方法集,而不是用[]Trip作为参数的所有东西来膨胀它.(例如,我建议DrawTripsOnTheGlobe(t Trips)不要将其作为Trips的方法.)
为了让自己平静下来,标准包中有很多这样的切片类型:
http://golang.org/pkg/sort/#Float64Slice
http://golang.org/pkg/sort/#IntSlice
http://golang.org/pkg/encoding/json/#RawMessage