Mohamad-Jaafar NEHME
Mohamad-Jaafar NEHME

Reputation: 1215

How to use a custom type of Slice in a Receiver Method

I am new to Golang, and I know that a Receiver Method should be called by reference not by value. But the weird thing is that after naming a slice type, this is not working!!

I named a set of processes as Group, where Process is a struct of whatever content.

type Group []Process

A Group has a set of related methods in which I use them commonly through receiver methods. This Search function is just a simple sample.

func (G *Group) Search(addr string) (*Process, error) {

    for _, ps := range *G {

        if ps.Address == addr {

            return &ps, nil
        }
    }
    return nil, errors.New("Group: Address Not found")
}

Then I call it by

p, err := group.Search(address)

p can be changed normally. But the changes are affecting only p (which is not really pointing to a slice element of the Group), not the slice element in Group.

Question: How to use a custom type of Slice in a Receiver Method.

Upvotes: 1

Views: 923

Answers (1)

hobbs
hobbs

Reputation: 239890

There's nothing wrong with how you're using a slice type as a receiver. There is something wrong with your loop and how you're returning a pointer. Change

for _, ps := range *G {
    if ps.Address == addr {
        return &ps, nil
    }
}

into

for i, ps := range *G {
    if ps.Address == addr {
        return &(*G)[i], nil
    }
}

and it should work — you'll be returning a pointer into the slice, instead of a pointer to a local variable.

Upvotes: 2

Related Questions