Golang reflect.Uint()函数及其示例
Go语言提供了内置的支持,可以通过反射包实现运行时反射,从而允许程序使用任意类型的对象进行操作。 Golang中的 reflect.Uint() 函数用于获取v的基础值,作为uint64。 要访问此函数,需要在程序中导入reflect包。
语法:
func (v Value) Uint() uint64
参数: 此函数不接受任何参数。
返回值: 此函数返回v的基础值,作为uint64。
下面的示例说明了在Golang中使用上述方法的用法:
示例1:
// Golang程序演示
// reflect.Uint()函数
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(“??? ”???“。)
返回nil
}
switch a.Kind() {
case reflect.Int,reflect.Int8,reflect.Int16,
reflect.Int32,reflect.Int64:
返回 []reflect.Value {reflect.ValueOf(a.Int() + b.Int())}
case reflect.Uint,reflect.Uint8,reflect.Uint16,
reflect.Uint32,reflect.Uint64:
返回 []reflect.Value {reflect.ValueOf(a.Uint() + b.Uint())}
case reflect.Float32,reflect.Float64:
返回 []reflect.Value {reflect.ValueOf(a.Float() + b.Float())}
case reflect.String:
返回 []reflect.Value {reflect.ValueOf(a.String() + b.String())}
默认:
返回 []reflect.Value {}
}
}
func makeSum(fptr interface{}) {
fn := reflect.ValueOf(fptr).Elem()
v := reflect.MakeFunc(fn.Type(),sum)
fn.Set(v)
}
// 主函数
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”))
}
输出:
3
5.599999904632568
GeeksforGeeks
示例2:
// Golang程序演示
// reflect.Uint()函数
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(“??? ”???“。)
返回nil
}
switch a.Kind() {
case reflect.Int,reflect.Int8,reflect.Int16,
reflect.Int32,reflect.Int64:
返回 []reflect.Value {reflect.ValueOf(a.Int() + b.Int())}
case reflect.Uint,reflect.Uint8,reflect.Uint16,
reflect.Uint32,reflect.Uint64:
返回 []reflect.Value {reflect.ValueOf(a.Uint() + b.Uint())}
case reflect.Float32,reflect.Float64:
返回 []reflect.Value{reflect.ValueOf(a.Float() + b.Float())}
case reflect.String:
返回 []reflect.Value {reflect.ValueOf(a.String() + b.String())}
默认:
返回 []reflect.Value {}
}
}
func makeSum(fptr interface{}) {
fn := reflect.ValueOf(fptr).Elem()
v := reflect.MakeFunc(fn.Type(),sum)
fn.Set(v)
}
// 主函数
func main() {
var stringSum func(string, string) string
makeSum(&stringSum)
fmt.Println(stringSum(“ Value_1:”,“ Geeks_1”))
}
输出:
Value_1 : 极客_1