Alexandr Butenko
Alexandr Butenko

Reputation: 3

How to pass an struct array to my struct function

So, i have my slice renamed for using in functions, which one connected to array (like a class methods).

type Points []Point


func (p Points) Isset(ip Point) bool {
     for _, i := range p {
         if i.Hash == ip.Hash {
             return true
         }
     }
     return false
}

But it's doesn't matter, coz in another function, which one tried to pass slice with type Points, i have some trouble...

Here is example:

func (p Points) Merge(ip Points) {
    fmt.Println(p)
}

In first function - i can access to my p variable as array. In second - p - just empty array. But if i change type of passed variable - everything will be fine.

What should i do... I need to specify me merge function. And this solution look's like awesome, but doesn't work.

Upvotes: 0

Views: 64

Answers (2)

sberry
sberry

Reputation: 131968

I am not sure I understand, this is a play example showing both functions working as expected as far as I can tell.

https://play.golang.org/p/n5ch-Wqbil

Perhaps you are running into some problem calling one function from the other (like calling Isset from Merge maybe?) In that case @Games' answer will probably still apply.

EDIT this example show what I think you are probably trying to do. https://play.golang.org/p/CNEt-poKdN and it seems to work just fine (though has N^2 time performance)

Upvotes: 2

Nafiul Islam
Nafiul Islam

Reputation: 82440

This is because you need to say that Points is a reference to an instance of Points. You can do this by the following:

func (p *Points) Isset(ip Point) bool {
     for _, i := range p {
         if i.Hash == ip.Hash {
             return true
         }
     }
     return false
}

Notice how we set *Points instead of Points. This tells go that we want to work with the instance of the Points struct that we have called the method from.

Upvotes: 1

Related Questions