Golang reflect.Interface()函数的示例
Go语言提供了内置支持运行时反射的实现,通过reflect包使程序可以操纵任意类型的对象。在Golang中, reflect.Interface() 函数用于将v的当前值作为interface{}返回。要访问此函数,需要在程序中导入reflect包。
语法:
func (v Value) Interface() (i interface{})
参数: 此函数仅接受一个参数。
- i : 该参数是interface{}类型
返回值: 此函数将v的当前值作为interface{}返回。
以下示例说明了在Golang中使用以上方法的用法:
示例1:
// Golang程序演示
// reflect.Interface()函数
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
t := reflect.TypeOf(5)
//使用Interface方法
arr := reflect.ArrayOf(4, t)
inst := reflect.New(arr).Interface().(*[4]int)
for i := 1; i <= 4; i++ {
inst[i-1] = i*i
}
fmt.Println(inst)
}
输出:
&[1 4 9 16]
示例2:
// Golang程序演示
// reflect.Interface()函数
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
var str []string
var v reflect.Value = reflect.ValueOf(&str)
v = v.Elem()
v = reflect.Append(v, reflect.ValueOf("a"))
v = reflect.Append(v, reflect.ValueOf("b"))
v = reflect.Append(v, reflect.ValueOf("c"), reflect.ValueOf("j, k, l"))
fmt.Println("Our value is a type of :", v.Kind())
vSlice := v.Slice(0, v.Len())
vSliceElems := vSlice.Interface()
fmt.Println("With the elements of : ", vSliceElems)
}
输出:
Our value is a type of : slice
With the elements of : [a b c j, k, l]
极客教程