Golang reflect.String() 函数及示例

Golang reflect.String() 函数及示例

Go 语言提供了内置支持的运行时反射实现,通过 reflect 包可帮助程序操作任意类型的对象。Golang 中的 reflect.String() 函数用于获取字符串 v 的基础值,作为字符串。要访问此函数,需要在程序中导入 reflect 包。

语法:

func (v Value) String() string

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

返回值: 此函数作为字符串返回字符串 v 的基础值。

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

示例1:

// Golang program to illustrate
// reflect.String() Function 
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function 
func main() {
   
    var k = reflect.TypeOf(0)
    var e = reflect.TypeOf("")
       
    //use of String method
    fmt.Println(reflect.FuncOf([]reflect.Type{k}, 
              []reflect.Type{e}, false).String())
} 

输出:

func(int) string

示例2:

// Golang program to illustrate
// reflect.String() Function 
   
package main
    
import (
    "fmt"
    "reflect"
)
   
type Struct1 struct {
    Var1       string
    Var2       string
    Var3       float64
    Var4       float64
}
   
// Main function 
func main() {
    NewMap := make(map[string]*Struct1)
    NewMap["abc"] = &Struct1{"abc", "def", 1.0, 2.0}
    subvalMetric := "Var1"
       
    for _, Value:= range NewMap {
        s := reflect.ValueOf(&Value).Elem()
      
    // use of String() method
        println(s.String())
        println(s.Elem().String())
           
        metric := s.Elem().FieldByName(subvalMetric).Interface()
        fmt.Println(metric)
    }
       
} 

输出:

<*main.Struct1 Value>

abc

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程