douzi7219 2015-07-17 10:11
浏览 140

GoLang约定-从切片创建自定义类型

Is it a good idea to create own type from a slice in Golang?

Example:

type Trip struct {
    From   string
    To     string
    Length int
}

type Trips []Trip // <-- is this a good idea?

func (trips *Trips) TotalLength() int {
    ret := 0
    for _, i := range *trips {
        ret += i.Length
    }

    return ret
}

Is it somehow a convention in Golang to create types like Trips in my example? Or it is better to use []Trip in the whole project? Any pros and cons?

  • 写回答

2条回答 默认 最新

  • dousi3362 2015-07-17 10:45
    关注

    There's no convention, as far as I am aware of. It's OK to create a slice type if you really need it. In fact, if you ever want to sort your data, this is pretty much the only way: create a type and define the sort.Interface methods on it.

    Also, in your example there is no need to take the address of Trips since slice is already a "fat pointer" of a kind. So you can simplify your method to:

    func (trips Trips) TotalLength() (tl int) {
        for _, l := range trips {
            tl += l.Length
        }
        return tl
    }
    
    评论

报告相同问题?