0

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.

1
  • Please show a running example which demonstrates your problem. Commented May 4, 2016 at 9:15

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

5 Comments

Magic... Can't repeat on my laptop. Keep trying.
When you say "Can't repeat on my laptop", what does that mean? Can you paste your entire code into a playground and link it in your question?
How would you create an append function for Points, where you can just do Points.Append(Point)?
@GamesBrainiac You would certainly need a pointer receiver in that case since you would be modifying the receiver.
Oh my god... I'am so sorry, but i just create a slice of points like var res Points in another function... And this one a cause, i guess. Now everything works perfect.
1

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.

2 Comments

Oh wait, but this function working well. And *Points doesn't working, coz we using type as alias for slice. Merge doesn't working, not Isset.
@AlexandrButenko see if the same change for Merge works now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.