GoLang conventions - create custom type from slice
Asked Answered
F

2

14

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?

Flapjack answered 17/7, 2015 at 10:11 Comment(1)
Yes,if you will understand that such Trips. Experts recommend to name the types in the context of the problem being solved.Exequatur
P
17

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
}
Papert answered 17/7, 2015 at 10:45 Comment(1)
In this case we could just write that method in one line as func (trips Trips) TotalLenght() int {return len(trips)}Edomite
L
8

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

Lordosis answered 17/7, 2015 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.