1 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
更新:這個(gè)答案曾經(jīng)包含兩種解決問(wèn)題的方法:我有點(diǎn)笨拙的方法,DaveC的更優(yōu)雅的方法。這是他更優(yōu)雅的方式:
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(), ":"))
}
游樂(lè)場(chǎng):https : //play.golang.org/p/FxsUo1vu6L
- 1 回答
- 0 關(guān)注
- 253 瀏覽
添加回答
舉報(bào)