Skip to content

Instantly share code, notes, and snippets.

@SuvidhaMalaviya
Created January 28, 2023 16:56
Show Gist options
  • Save SuvidhaMalaviya/cc919bcc52869ead63b5d0d875c97ff8 to your computer and use it in GitHub Desktop.
Save SuvidhaMalaviya/cc919bcc52869ead63b5d0d875c97ff8 to your computer and use it in GitHub Desktop.
reflection-2-go-lang
package main
import (
"fmt"
"reflect"
)
type MyStruct struct {
Name string
Age int
}
func main() {
// Get the type of the struct
t := reflect.TypeOf(MyStruct{})
// Create a new struct object using reflect.New()
v := reflect.New(t)
// Set the struct fields using the Elem() method
v.Elem().Field(0).SetString("John")
v.Elem().Field(1).SetInt(30)
// Print the struct object
fmt.Println(v.Elem().Interface()) // Output: {John 30}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment