Skip to content
Related Articles

Related Articles

reflect.StructOf() 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.StructOf() Function in Golang is used to get the struct type containing fields. To access this function, one needs to imports the reflect package in the program.

Syntax:

func StructOf(fields []StructField) Type

Parameters: This function takes only one parameters of StructFields( fields ).

Return Value: This function returns the struct type containing fields.

Below examples illustrate the use of above method in Golang:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.SliceOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function
func main() {
  
    // use of StructOf method
    typ := reflect.StructOf([]reflect.StructField{
        {
            Name: "Height",
            Type: reflect.TypeOf(float64(0)),
        },
        {
            Name: "Name",
            Type: reflect.TypeOf("abc"),
        },
    })
  
    fmt.Println(typ)
  
}

chevron_right


Output:

struct { Height float64; Name string }

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.SliceOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function
func main() {
  
    // use of StructOf method
    tt:= reflect.StructOf([]reflect.StructField{
        {
            Name: "Height",
            Type: reflect.TypeOf(0.0),
            Tag:  `json:"height"`,
        },
        {
            Name: "Name",
            Type: reflect.TypeOf("abc"),
            Tag:  `json:"name"`,
        },
    })
  
    fmt.Println(tt.NumField()) 
    fmt.Println(tt.Field(0))
    fmt.Println(tt.Field(1))
  
}

chevron_right


Output:

2
{Height  float64 json:"height" 0 [0] false}
{Name  string json:"name" 8 [1] false}
My Personal Notes arrow_drop_up
Recommended Articles
Page :