Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

reflect.Tag.Lookup() Function in Golang with Examples

  • Last Updated : 28 Apr, 2020

Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Tag.Lookup() Function in Golang is used to find the value associated with key in the tag string, an empty string is returned if there is no such key in the tag and to determine whether a tag is explicitly set to the empty string. To access this function, one needs to imports the reflect package in the program.

Syntax:

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

Parameters: This function takes two parameters of string type (value) and bool type(ok).

Return Value: This function returns the value associated with key in the tag string and the value was explicitly set.

Below examples illustrate the use of the above method in Golang:



Example 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)")
        }
    }    
}

Output:

123456
(Empty)
(Non specific)

Example 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))    
}

Output:

Get method: 1
Lookup method: - false



My Personal Notes arrow_drop_up