添加到golang中类型的匿名切片
我想添加一些附加到切片上的帮助器方法。 因此,我创建了一个类型为[]*MyType 有什么方法可以添加到MyTypes的切片中吗?append将无法识别该切片添加到golang中类型的匿名切片,go,Go,我想添加一些附加到切片上的帮助器方法。 因此,我创建了一个类型为[]*MyType 有什么方法可以添加到MyTypes的切片中吗?append将无法识别该切片 package main import "fmt" type MyType struct{ Name string Something string } type MyTypes []*MyType func NewMyTypes(myTypes ...*MyType)*MyTypes{ var s
package main
import "fmt"
type MyType struct{
Name string
Something string
}
type MyTypes []*MyType
func NewMyTypes(myTypes ...*MyType)*MyTypes{
var s MyTypes = myTypes
return &s
}
//example of a method I want to be able to add to a slice
func(m MyTypes) Key() string{
var result string
for _,i := range m{
result += i.Name + ":"
}
return result
}
func main() {
mytype1 ,mytype2 := MyType{Name:"Joe", Something: "Foo"}, MyType{Name:"PeggySue", Something: "Bar"}
myTypes:= NewMyTypes(&mytype1,&mytype2)
//cant use it as a slice sadface
//myTypes = append(myTypes,&MyType{Name:"Random", Something: "asdhf"})
fmt.Println(myTypes.Key())
}
我不想用另一种类型来包装它并命名param,即使我正在这么做。。因为json,编组可能会有所不同
添加到MyTypes切片的方法是什么
我真的希望能够向切片添加一个方法,这样它就可以实现一个特定的接口,而不会影响编组。。有其他更好的方法吗
谢谢更新:这个答案曾经包含了两种解决问题的方法:我有点笨重的方法,更优雅的方法。以下是他更优雅的方式:
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(), ":"))
}
操场:是的,这也是可以接受的。。非常感谢!(Gah总是忘记通道和片是ref类型:P)根本不需要创建
Append
方法并强制转换任何内容。这是因为您错误地使用了指向不必要片的指针。正如编写的那样,您只需要执行*myTypes=append(*myTypes,/*which*/)
。最好不要使用指向切片的指针,除非你知道自己在做什么:谢谢戴夫,我觉得现在没看到有点傻。完全有道理。。干杯