1 回答
TA贡献1805条经验 获得超10个赞
更新:这个答案曾经包含两种解决问题的方法:我有点笨拙的方法,DaveC的更优雅的方法。这是他更优雅的方式:
package main
import (
"fmt"
"strings"
)
type MyType struct {
Name string
Something string
}
type MyTypes []*MyType
func NewMyTypes(myTypes ...*MyType) MyTypes {
return myTypes
}
//example of a method I want to be able to add to a slice
func (m MyTypes) Names() []string {
names := make([]string, 0, len(m))
for _, v := range m {
names = append(names, v.Name)
}
return names
}
func main() {
mytype1, mytype2 := MyType{Name: "Joe", Something: "Foo"}, MyType{Name: "PeggySue", Something: "Bar"}
myTypes := NewMyTypes(&mytype1, &mytype2)
myTypes = append(myTypes, &MyType{Name: "Random", Something: "asdhf"})
fmt.Println(strings.Join(myTypes.Names(), ":"))
}
游乐场:https : //play.golang.org/p/FxsUo1vu6L
- 1 回答
- 0 关注
- 211 浏览
添加回答
举报