Golang reflect.Len()函数的使用及示例

Golang reflect.Len()函数的使用及示例

Go语言提供内置的反射实现支持,允许程序使用reflect包操作任意类型的对象。 Golang中的 reflect.Len() 函数用于获取v的长度。要访问此函数,需要在程序中导入reflect包。

语法:

func(v Value) Len() int

参数: 此函数不接受任何参数。

返回值: 此函数返回v的长度。

以下示例说明了在Golang中使用上述方法的方式:

示例1:

// Golang程序演示 
// reflect.Len()函数 
package main
import (
    "fmt"
    "reflect"
)
func main() {
    c := make(chan int, 1)
    vc := reflect.ValueOf(c)
    succeeded := vc.TrySend(reflect.ValueOf(123))
    // 使用Len()方法
    fmt.Println(succeeded, vc.Len(), vc.Cap())
} 

输出:

true 1 1

示例2:

// Golang程序演示 
// reflect.Len()函数 
package main 
import ( 
    "fmt"
    "reflect"
)
func main() {
    data := []string{"Geeks1", "Geeks2", "Geeks3"}
    test(data)
    data1 := []int{1, 2, 3}
    test(data1)
}

func test(t interface{}) {
    switch reflect.TypeOf(t).Kind() {
    case reflect.Slice:
        s := reflect.ValueOf(t)          
        for i := 0; i < s.Len(); i++ {
            fmt.Println(s.Index(i))
        }
    }
} 

输出:

Geeks1
Geeks2
Geeks3
1
2
3

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程