Open In App

reflect.CanInterface() Function in Golang with Examples

Last Updated : 23 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.CanInterface() Function in Golang is used to check whether Interface can be used without panicking. To access this function, one needs to imports the reflect package in the program.

Syntax:
func (v Value) CanInterface() bool
Parameters: This function does not accept any parameters. Return Value: This function returns the boolean value.

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

Example 1:

C
// Golang program to illustrate
// reflect.CanInterface() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function  
func main() {
    
    num := 6
    meta := reflect.ValueOf(num)
    
    // use of CanInterface() method
    fmt.Println("canInterface:", meta.CanInterface() == true)
}        

Output:

canInterface: true

Example 2:

C
// Golang program to illustrate
// reflect.CanInterface() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function  
func main() {
    
    string := "ABC"
    meta := reflect.ValueOf(&string)
    
    // use of CanInterface() method
    fmt.Println("canInterface:", meta.CanInterface() == false)
}

Output:

canInterface: false

Next Article
Article Tags :

Similar Reads