Sobes.tech
Junior

Kā īstenot kopu (set) Go valodā?

sobes.tech AI

Atbilde no AI

Go valodā nav iebūvēta datu tipa "kopas". To var īstenot, izmantojot map.

// Rindu kopas īstenojums
type Set map[string]struct{}

// Elementa pievienošana
func (s Set) Add(item string) {
	s[item] = struct{}{} // Izmantojam struct{}, lai neaizņemtu papildu atmiņu
}

// Elementa dzēšana
func (s Set) Remove(item string) {
	delete(s, item)
}

// Pārbaude, vai elements ir
func (s Set) Contains(item string) bool {
	_, ok := s[item]
	return ok
}

// Visu elementu iegūšana (nekārtota)
func (s Set) ToSlice() []string {
	slice := make([]string, 0, len(s))
	for item := range s {
		slice = append(slice, item)
	}
	return slice
}