type Set map[string]struct{}
emptystruct := struct{}{}
setstruct := make(Set)
fmt.Println("Size of Empty Struct:", unsafe.Sizeof(emptystruct))
fmt.Println("Size of set:", unsafe.Sizeof(setstruct))
Size of Empty Struct: 0
Size of set: 8
-Adding an item to the set will be the same as adding an item to any type of map.
func main() {
s := make(Set)
//add items
s["Item1"] = struct{}{}
s["Item2"] = struct{}{}
fmt.Println(getSetValues(s))
}
func getSetValues(s Set) []string {
var retVal []string
for k, _ := range s {
retVal = append(retVal, k)
}
return retVal
}
Set Fuction
var exists = struct{}{}
func (s *Set) Add(value string) {
s[value] = exists
}
func (s *Set) Remove(value string) {
delete(s.m, value)
}
func (s *Set) Contains(value string) bool {
_, c := s.m[value]
return c
}
Go Channel concurrenct with EmptyStruct
package main
import "fmt"
var battle = make(chan string)
func warrior(name string, done chan struct{}) {
select {
case opponent := <-battle:
fmt.Printf("%s beat %s\n", name, opponent)
case battle <- name:
// I lost :-(
}
done <- struct{}{}
}
func main() {
done := make(chan struct{})
langs := []string{"Go", "C", "C++", "Java", "Perl", "Python"}
for _, l := range langs { go warrior(l, done) }
for _ = range langs { <-done }
}
Print Result 1
C++ beat Python
Go beat C
Perl beat Java
Print Result 2
Python beat Go
Java beat Perl
C++ beat C
package main
import "fmt"
var signal = make(chan string)
func main() {
done := make(chan struct{})
values := []int{1, 2, 3, 4, 5, 6, 7, 8}
for _, n := range values {
go randomNumber(n, done)
}
for _ = range values {
<-done
}
}
func randomNumber(n int, done chan struct{}) {
fmt.Println(n)
done <- struct{}{}
}