同一个channel, 我需要在多个goroutine中send, 在一个goroutine中receive, 并且我可以随时关闭这个channel, 问题是如果我关闭channel后还有send, 就会导致一个panic.

网上找到的一个方法是panic后再recover

func SafeSend(ch chan T, value T) (closed bool) {

    defer func() {

        if recover() != nil {

            // the return result can be altered 

            // in a defer function call

            closed = true

        }

    }()


    ch <- value // panic if ch is closed

    return false // <=> closed = false; return

}

因为不想用recover,问一下还有没有更加优雅的方式去实现