Welcome To Golang By Example

Empty struct in GO

Empty struct struct{} in GO doesn’t occupy any memory. It is of zero byte.

Below are some of the uses of empty struct

Eg. One example is in while implementing Null Object Design Pattern in Go. The Null object doesn’t have any data. See an example of Null Object Design Pattern in GO – https://golangbyexample.com/null-object-design-pattern-golang/

Eg: In context package of GO we have cancelCtx which is represented as below. See done channel is using an empty struct as it is only used for notifying cancellation and has no data value.

type cancelCtx struct {
    Context
    mu       sync.Mutex            // protects following fields
    done     chan struct{}         // created lazily, closed by first cancel call
    children map[canceler]struct{} // set to nil by the first cancel call
    err      error                 // set to non-nil by the first cancel call
}

See this link for set implementation in golang – https://golangbyexample.com/set-implementation-in-golang/

package main

import (
    "fmt"
    "time"
)

func main() {
    done := make(chan struct{}, 4)
    for i := 0; i < 4; i++ {
        go runasync(done)
    }
    for i := 0; i < 4; i++ {
        <-done
    }
    close(done)
    fmt.Printf("Finish")
}

func runasync(done chan<- struct{}) {
    time.Sleep(1 * time.Second)
    done <- struct{}{}
    return
}