Created
January 28, 2023 16:56
-
-
Save SuvidhaMalaviya/cc919bcc52869ead63b5d0d875c97ff8 to your computer and use it in GitHub Desktop.
reflection-2-go-lang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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