02/02 Study Daily record

손진성·2022년 2월 3일
0

Set집합

what is set?

  • A data type that stores values.
  • Values are never repeated.
  • Values are unordered.
  • It is a computer implementation of the mathematical concept of a finite set.
type Set map[string]struct{}
  • a struct holds almost no memory.
	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
}
  • by using setSetValues function, we can check what keys(values) are in set.

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
}
  • we can implement rest of the basic operations on set

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
  1. What is struct{}{}?
  • it is a type struct{} with {}
  1. Why Results are mixed?
  • Because Warrier Go routine was declared, values were input at the same time.
  • As a result, it shows like that
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{}{}
}
 
  • go.dev/play/p/08yTucr-p-o
profile
Gopyther

0개의 댓글