Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Close()函数用于关闭通道v。要访问该函数,需要在程序中导入reflect 包。
Syntax:
Parameters: This function does not accept any parameters.
Return Value: This function does not return any value.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func (v Value) Close()
输出:
// Golang program to illustrate
// reflect.Close() Function
package main
import (
"fmt"
"reflect"
)
type T int
func IsClosed(ch <-chan T) bool {
select {
case <-ch:
return true
default:
}
return false
}
func main() {
c := make(chan T)
vc := reflect.ValueOf(c)
fmt.Println(IsClosed(c))
// use of Close() method
vc.Close()
fmt.Println(IsClosed(c))
}
示例 2:
false
true
输出:
// Golang program to illustrate
// reflect.Close() Function
package main
import (
"fmt"
"reflect"
)
func main() {
c := make(chan int, 1)
vc := reflect.ValueOf(c)
succeeded := vc.TrySend(reflect.ValueOf(123))
fmt.Println(succeeded, vc.Len(), vc.Cap())
vSend, vZero := reflect.ValueOf(789), reflect.Value{}
branches := []reflect.SelectCase{
{Dir: reflect.SelectDefault, Chan: vZero, Send: vZero},
{Dir: reflect.SelectRecv, Chan: vc, Send: vZero},
{Dir: reflect.SelectSend, Chan: vc, Send: vSend},
}
selIndex, vRecv, sentBeforeClosed := reflect.Select(branches)
fmt.Println(selIndex)
fmt.Println(sentBeforeClosed)
fmt.Println(vRecv.Int())
// use of Close() method
vc.Close()
}