How to create a set of objects in Go

1 Answer

0 votes
package main

import "fmt"

type MyObject struct {
    ID   int
    Name string
}

func main() {
    // Initialize the set
    set := make(map[MyObject]struct{})

    // Add objects to the set
    obj1 := MyObject{ID: 1, Name: "Object1"}
    obj2 := MyObject{ID: 2, Name: "Object2"}

    set[obj1] = struct{}{}
    set[obj2] = struct{}{}
    
    fmt.Println("Print the set:")
    for obj := range set {
        fmt.Println(obj)
    }

    // Check if an object is in the set
    obj3 := MyObject{ID: 1, Name: "Object1"}
    if _, exists := set[obj3]; exists {
        fmt.Println("\nobj3 is in the set\n")
    } else {
        fmt.Println("\nobj3 is not in the set\n")
    }

    // Remove an object from the set
    delete(set, obj1)

    fmt.Println("Print the set:")
    for obj := range set {
        fmt.Println(obj)
    }
}



/*
run:

Print the set:
{1 Object1}
{2 Object2}

obj3 is in the set

Print the set:
{2 Object2}

*/

 



answered Apr 22, 2025 by avibootz

Related questions

1 answer 225 views
1 answer 171 views
1 answer 110 views
1 answer 86 views
...