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

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.Get() 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. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (tag StructTag) Get(key string) string

Parameters: This function takes one parameters of string type, i.e. key.

Return Value: This function returns the value associated with key in the tag string.

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



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

auto_increment:"true" increment:"1"

Get method: 1

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Best Platform : GeeksforGeeks



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.