在golang中向匿名切片类型添加元素

3

我想要在一个切片上添加一些辅助方法。所以我创建了一个类型为 []*MyType 的变量。 有没有办法在 MyTypes 切片中添加元素?append 方法无法识别该切片。

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())
}

我不想把它包装成另一种类型并命名参数,尽管我有点这样做...因为JSON编组可能会有所不同。
如何向MyTypes切片添加内容?
我真的希望能够仅添加一个方法到切片中以使其实现特定接口而不影响编组..是否有更好的不同方法?
谢谢

1
这是因为您错误地使用了指向切片的指针,而这是不必要的。按照所写的方式,您只需要执行 *myTypes = append(*myTypes, /*whatever*/) 。最好不要使用指向切片的指针,除非您知道自己在做什么:https://play.golang.org/p/FxsUo1vu6L - Dave C
谢谢Dave,现在我感觉有点傻,没有看到那个。完全有道理。干杯。 - mcbain83
1个回答

2

更新:此回答曾经包含两种解决问题的方式:我比较繁琐的方式和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(), ":"))
}

Playground: https://play.golang.org/p/FxsUo1vu6L


好的,那也可以接受。太棒了,谢谢!(啊,老是忘记通道和切片是引用类型:P) - mcbain83
1
完全没有必要编写“Append”方法并进行任何类型转换。 - Dave C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接