簡體   English   中英

在golang中添加類型中的匿名切片

[英]Adding to an anonymous slice in a type in golang

我想添加一些輔助方法附加到切片上。 所以我創建了一個[] * MyType的類型是否有任何方法可以添加到MyTypes的那一片? 追加將無法識別切片。

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切片的方法是什么?

我真的希望能夠將一個方法添加到切片中,這樣它就可以實現一個特定的接口,而不會影響編組。是否有更好的方法?

謝謝

更新:這個答案曾經包含兩種解決問題的方法:我有點笨重的方式, 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM