Sobes.tech
Middle

What happens if you close an already closed channel in Go?

sobes.tech AI

Answer from AI

A panic will occur during execution (panic).

Closing a channel is an operation that should only be performed once. Re-closing signals a potential logical error in the program related to incorrect channel state management.

package main

import (
	"fmt"
)

func main() {
	ch := make(chan int)

	close(ch) // First close - OK

	fmt.Println("Channel closed successfully.")

	// Attempting to close again will cause a panic
	// close(ch)
	// fmt.Println("This line will not be executed if the previous line is uncommented.")
}