Go語言提供了運行時反射的內置支持實現,並允許程序借助反射包來操縱任意類型的對象。 Golang中的reflect.Tag.Get()函數用於查找與標簽字符串中的鍵關聯的值,如果標簽中沒有此類鍵,則返回一個空字符串。要訪問此函數,需要在程序中導入反射包。
用法:
func (tag StructTag) Get(key string) string
參數:此函數采用一個字符串類型的參數,即key。
返回值:此函數返回與標簽字符串中的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
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 reflect.Tag.Get() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。