📜  Golang 中的reflect.Interface()函数示例

📅  最后修改于: 2021-10-25 02:41:35             🧑  作者: Mango

Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Interface()函数用于获取v 的当前值作为接口{}。要访问此函数,需要在程序中导入反射包。

下面的例子说明了上述方法在 Golang 中的使用:

示例 1:

func (v Value) Interface() (i interface{})

输出:

// Golang program to illustrate
// reflect.Interface() Function 
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function 
func main() {
    t := reflect.TypeOf(5)
       
    //use of Interface method
    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)
}

示例 2:

&[1 4 9 16]

输出:

// Golang program to illustrate
// reflect.Interface() Function
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function
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)
   
}