Golang reflect.Tag.Get() 函数的示例

Golang reflect.Tag.Get() 函数的示例

Go 语言提供了内置支持的运行时反射实现,通过 reflect 包允许程序操作任意类型的对象。Golang 中的 reflect.Tag.Get() 函数用于查找与标签字符串中的键关联的值,如果在标记中没有这样的键,则返回空字符串。要访问此函数,需要在程序中导入 reflect 包。

语法:

func (tag StructTag) Get(key string) string

参数: 此函数接受一个字符串类型的参数,即 key。

返回值: 此函数返回与标记字符串中的键关联的值。

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

示例 1:

// Golang program to illustrate
// reflect.Tag.Get() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
type Employee struct {
    ID      string `auto_increment:"true" increment:"1"`
    Name    string `varchar: "255"`
    Surname string `"varchar: "255"`
}
  
// Main function
func main() {
    e := Employee{}
    // c variable represents table columns
    c := reflect.TypeOf(e).Field(0).Tag
    fmt.Printf("%s\n\n", c)
  
    // use of Get method
    g := c.Get("increment")
    fmt.Printf("Get method: %s\n", g)
} 

输出:

auto_increment:"true" increment:"1"

Get method: 1

示例 2:

// Golang program to illustrate
// reflect.Tag.Get() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function 
func main() {
    type tag struct {
        val string `Value_1:"GeeksforGeeks" Value_2:"Best Platform :"`
    }
  
    src := tag {}
    st := reflect.TypeOf(src)
    field := st.Field(0)
      
    // use of Get method
    fmt.Println(field.Tag.Get("Value_2"), field.Tag.Get("Value_1"))
  
} 

输出:

Best Platform : GeeksforGeeks

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程