Open In App

reflect.Close() Function in Golang with Examples

Last Updated : 03 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Close() Function in Golang is used to close the channel v. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (v Value) Close()

Parameters: This function does not accept any parameters.

Return Value: This function does not return any value.

Below examples illustrate the use of the above method in Golang:

Example 1:




// 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))
}                    


Output:

false
true

Example 2:




// 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()
   
}       


Output:

true 1 1
1
true
123


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads