Method on slice

Asked by At

Although I think the problem I have is not correctly described in the heading it is the only way I am able to describe it now.

I have a struct Mini which is defined in another file. A set of Minis should be described as a slice. As I want to change some fields of the Mini struct when it is appended to the slice custom functions for append are needed.

Until now I got the following code:

import (
    "fmt"
    "reflect"
)

//Minis is a slice of all Minis
type Minis struct {
    AllMinis []*Mini
}

//Append adds a new Mini to the Minis slice
func (m *Minis) Append(n *Mini) {
    m.AllMinis = append(m.AllMinis, n)
}

This code works totally fine. But in my opinion a struct with just one field is kind of witless.

Is there any way to make a method on a struct or a more elegant solution in general?

Thanks!

1 Answers

4
ThunderCat On Best Solutions

Declare the type as a slice:

//Minis is a slice of all Minis
type Minis []*Mini

//Append adds a new Mini to the Minis slice
func (m *Minis) Append(n *Mini) {
    *m = append(*m, n)
}

Run it on the playground.

concat panics because QForename passes a nil slice pointer as the receiver to concat. Fix by using a non-nil pointer:

func (m *Minis) QForename(q string) *Minis {
    var matches Minis
    for _, n := range *m {
        if n.Forename == q {
            matches.concat(n)
        }
    }
    return &matches
}