빈 구조체 struct{}
struct{} 는 필드가 없는 빈 구조체 타입을 정의한다.
struct{}{} 란 아무것도 정의되어있지 않은 struct를 생성하는 것이다.
일반 구조체를 만드는 것과 비교해 보면 알기 쉽다.
package main
import (
"fmt"
)
func main() {
person := struct {
Name string
Age int
}{"peter", 10}
emptystruct := struct{}{}
fmt.Println(person)
fmt.Println(emptystruct)
// {peter 10}
// {}
}
빈 구조체는 필드가 없기 때문에 메모리 효율이 좋고, 다양한 상황에서 유용하게 사용할 수 있다.
struct{} 는 보통 세 가지 방법으로 사용한다.
1. 채널에서 신호로 사용
특정 고루틴의 작업이 끝났을 때 작업이 완료되었음을 알리기 위해 사용한다.
package main
import (
"fmt"
"time"
)
func main() {
done := make(chan struct{})
go func() {
defer func() { done <- struct{}{} }()
time.Sleep(3 * time.Second)
fmt.Println("Hello World!")
}()
<-done
}
<-done이 없다면 새로 만들어진 고루틴의 Sleep 시간이 끝나기 전에 메인 고루틴이 끝나게 되면서 "Hello World"는 출력되지 않고 프로그램이 종료된다.
<-done 이 있으므로 채널에 값이 들어올 때 까지 메인 고루틴이 블로킹되고, 새로 만들어진 고루틴의 defer가 실행된 이후 메인 고루틴도 종료된다.
다른 방법으로는 sync.WaitGroup을 사용할 수 있다.
2. Map으로 Set구현
Go는 Set 자료구조를 지원하지 않기 때문에 map과 struct{} 를 사용해 구현할 수 있다.
package main
import (
"fmt"
)
func main() {
set := make(map[string]struct{})
set["key"] = struct{}{}
if _, exists := set["key"]; exists {
fmt.Println(true)
}
}
3. 메서드 수신자로 사용
빈 구조체를 메서드 수신자로 사용하여 상태를 저장할 필요가 없는 메서드를 정의할 수 있다.
package main
import (
"fmt"
)
type MyStruct struct{}
func (m MyStruct) printHello() {
fmt.Println("hello")
}
func main() {
var m MyStruct
m.printHello()
}
'Go' 카테고리의 다른 글
[Go] 클로저 (0) | 2024.08.22 |
---|---|
[Go] 컨트리뷰트 도전 실패 (0) | 2024.06.10 |
[Go] multipart/form-data 전송, 수신 (0) | 2024.06.10 |
[Go] 테스트가능한 예시 (Testable Examples) (0) | 2024.06.05 |