reflect.FuncOf() Function in Golang with Examples
Last Updated :
28 Apr, 2020
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.FuncOf() Function in Golang is used to get the function type with the given argument and result types, i.e., if k represents int and e represents string, FuncOf([]Type{k}, []Type{e}, false) represents func(int) string. To access this function, one needs to imports the reflect package in the program.
Syntax:
func FuncOf(in, out []Type, variadic bool) Type
Parameters: This function takes three parameters of []Type type (in, out) and bool type( variadic ).
Return Value: This function returns the function type with the given argument and result types.
Below examples illustrate the use of above method in Golang:
Example 1:
package main
import (
"fmt"
"reflect"
)
func main() {
ta := reflect.ArrayOf(5, reflect.TypeOf(123))
tc := reflect.ChanOf(reflect.SendDir, ta)
tp := reflect.PtrTo(ta)
tf := reflect.FuncOf([]reflect.Type{ta},
[]reflect.Type{tp, tc}, false )
fmt.Println(tf)
}
|
Output:
func([5]int) (*[5]int, chan<- [5]int)
Example 2:
package main
import (
"fmt"
"reflect"
)
func main() {
var k = reflect.TypeOf(0)
var e = reflect.TypeOf( "" )
fmt.Println(reflect.FuncOf([]reflect.Type{k},
[]reflect.Type{e}, false ).String())
}
|
Output:
func(int) string
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...