doufunuo4787 2015-10-02 04:49
浏览 81
已采纳

在golang中的类型中添加到匿名切片

I want to add a few helper methods attached onto a slice. So I created a type which is of []*MyType Is there any way to add to that slice of MyTypes? append will not recognise the slice.

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

I don't want to wrap it in another type and name the param even though I'm sorta doing it.. Because of json marshalling will probably be different

What would be the way to add to the MyTypes slice?

I really want to just be able to add a method to a slice so it can implement a specific interface and not effect the marshalling.. Is there a different better way?

Thanks

  • 写回答

1条回答 默认 最新

  • dongwen9947 2015-10-02 05:01
    关注

    Update: This answer once contained two ways to solve the problem: my somewhat clunky way, the DaveC's more elegant way. Here's his more elegant way:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable