Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GoLang conventions - create custom type from slice

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?

like image 960
DHlavaty Avatar asked Jul 17 '15 10:07

DHlavaty


2 Answers

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
}
like image 143
Ainar-G Avatar answered Oct 23 '22 10:10

Ainar-G


If this is what your type is (a slice), it's just fine. It gives you an easy access to underlying elements (and allows for range iteration) while providing additional methods.

Of course you probably should only keep essential set of methods on this type and not bloating it with everything that would take []Trip as an argument. (For example I would suggest having DrawTripsOnTheGlobe(t Trips) rather than having it as a Trips' method.)

To calm your mind there are plenty of such slice-types in standard packages:

http://golang.org/pkg/net/#IP

http://golang.org/pkg/sort/#Float64Slice

http://golang.org/pkg/sort/#IntSlice

http://golang.org/pkg/encoding/json/#RawMessage

like image 8
tomasz Avatar answered Oct 23 '22 09:10

tomasz