Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Uint()函数用于获取v 的底层值,作为uint64。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function does not accept any parameter.
Return Value: This function returns the v’s underlying value, as a uint64.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func (v Value) Uint() uint64
输出:
// Golang program to illustrate
// reflect.Uint() Function
package main
import (
"fmt"
"reflect"
)
func sum(args []reflect.Value) []reflect.Value {
a, b := args[0], args[1]
if a.Kind() != b.Kind() {
fmt.Println("??? ????.")
return nil
}
switch a.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
return []reflect.Value{reflect.ValueOf(a.Int() + b.Int())}
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64:
return []reflect.Value{reflect.ValueOf(a.Uint() + b.Uint())}
case reflect.Float32, reflect.Float64:
return []reflect.Value{reflect.ValueOf(a.Float() + b.Float())}
case reflect.String:
return []reflect.Value{reflect.ValueOf(a.String() + b.String())}
default:
return []reflect.Value{}
}
}
func makeSum(fptr interface{}) {
fn := reflect.ValueOf(fptr).Elem()
v := reflect.MakeFunc(fn.Type(), sum)
fn.Set(v)
}
// Main function
func main() {
var intSum func(int, int) int64
var floatSum func(float32, float32) float64
var stringSum func(string, string) string
makeSum(&intSum)
makeSum(&floatSum)
makeSum(&stringSum)
fmt.Println(intSum(1, 2))
fmt.Println(floatSum(2.1, 3.5))
fmt.Println(stringSum("Geeksfor","Geeks"))
}
示例 2:
3
5.599999904632568
GeeksforGeeks
输出:
// Golang program to illustrate
// reflect.Uint() Function
package main
import (
"fmt"
"reflect"
)
func sum(args []reflect.Value) []reflect.Value {
a, b := args[0], args[1]
if a.Kind() != b.Kind() {
fmt.Println("??? ????.")
return nil
}
switch a.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
return []reflect.Value{reflect.ValueOf(a.Int() + b.Int())}
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64:
return []reflect.Value{reflect.ValueOf(a.Uint() + b.Uint())}
case reflect.Float32, reflect.Float64:
return []reflect.Value{reflect.ValueOf(a.Float() + b.Float())}
case reflect.String:
return []reflect.Value{reflect.ValueOf(a.String() + b.String())}
default:
return []reflect.Value{}
}
}
func makeSum(fptr interface{}) {
fn := reflect.ValueOf(fptr).Elem()
v := reflect.MakeFunc(fn.Type(), sum)
fn.Set(v)
}
// Main function
func main() {
var stringSum func(string, string) string
makeSum(&stringSum)
fmt.Println(stringSum("Value_1 : ","Geeks_1"))
}