當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang reflect.Tag.Lookup()用法及代碼示例

Go語言提供了運行時反射的內置支持實現,並允許程序借助反射包來操縱任意類型的對象。 Golang中的reflect.Tag.Lookup()函數用於查找與標簽字符串中的鍵相關聯的值,如果標簽中沒有此類鍵,則返回一個空字符串,並確定是否將標簽明確設置為空字符串。要訪問此函數,需要在程序中導入反射包。

用法:
func (tag StructTag) Lookup(key string) (value string, ok bool)

參數:此函數采用字符串類型(值)和布爾類型(確定)的兩個參數。

返回值:此函數返回與標簽字符串中的key關聯的值,並且該值已顯式設置。

以下示例說明了以上方法在Golang中的用法:



範例1:

// Golang program to illustrate 
// reflect.Tag.Lookup() Function  
  
package main 
  
import ( 
    "fmt"
    "reflect"
) 
  
// Main function  
func main() { 
    type S struct { 
        F0 string `val:"123456"` 
        F1 string `val:""` 
        F2 string 
    } 
  
    s:= S{} 
    st:= reflect.TypeOf(s) 
    for i:= 0; i < st.NumField(); i++ { 
        field:= st.Field(i) 
          
        // use of Lookup method 
        if value, ok:= field.Tag.Lookup("val"); ok { 
            if value == "" { 
                fmt.Println("(Empty)") 
            } else { 
                fmt.Println(value) 
            } 
        } else { 
            fmt.Println("(Non specific)") 
        } 
    }     
}

輸出:

123456
(Empty)
(Non specific)

範例2:

// Golang program to illustrate 
// reflect.Tag.Lookup() Function  
  
package main 
  
import ( 
    "fmt"
    "reflect"
    "strconv"
) 
  
type Temp struct { 
    ID string `auto_increment:"true" increment:"1"` 
    Name string `varchar:"255"` 
    Surname string `"varchar:"255"` 
} 
  
// Main function  
func main() { 
    v:= Temp{} 
    // c variable represents table columns 
    c:= reflect.TypeOf(v).Field(0).Tag 
      
    // g variable represents get 
    g:= c.Get("increment") 
    fmt.Printf("Get method:%s\n", g) 
      
    val, ok:= c.Lookup("auto_increments") 
    fmt.Printf("Lookup method:%s- %s", val, strconv.FormatBool(ok))     
}

輸出:

Get method:1
Lookup method:- false



相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 reflect.Tag.Lookup() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。