Determine if slice contains

Is there a genuinely simple way where, given the following:

package main

import (
	"fmt"
)

func main() {
	first_list := [] string { "52200","53233","54999","52096" }
	second_list := [] string { "67822", "67362", "52200", "42329" }	
	
}

I can easily tell that
(a) “52200” appears in both slices.
(b) “53233” only appears in the first_list

I’m sure you get the idea. I think I have been spoiled by .contain() just about everywhere else.

Thanks,

There is no direct support for sets or set intersection/difference operations in the language itself.

The traditionally way would be to constuct two maps of type map[int]bool (some would argue that map[int]struct{} is technically better) with the contents of your slices then write the set operations yourself, which is what most people tend to do.

However there is another option using Kevin Gillette’s set package.

The package is a little bit unusual, because not many people are prepared to think of slices as sets, but it does what it says on the tin.

@dfc

Thank you very much for the reply.

I was initially feeling a bit troubled that there was no func contains() type method built in but having Googled around and reading your answer a few times I gave it a try and actually its not too painful at all to implement. In fact I’m sure that if the problem I were trying to solve required several comparisons it would be super-easy to write a function.

I made, as an aide-memoire to myself, a little demo script here:

I think it embodies what you described as the ‘traditional’ way to solve the problem. Works for me :slight_smile:

Thanks again.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.