Skip to content

Instantly share code, notes, and snippets.

@kitz99
Created March 22, 2019 06:56
Show Gist options
  • Save kitz99/eb9f50f2cbc3f5f9afc8dc15128e9c6d to your computer and use it in GitHub Desktop.
Save kitz99/eb9f50f2cbc3f5f9afc8dc15128e9c6d to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
)
type User struct {
ID int
Email string `json:"email" yaml:"email_address"`
Data struct {
Key string
Value bool
}
}
func main() {
user := User{ID: 42}
aString := "This is a string variable"
// getting the reflect values for user and aString
reflectedUserValue := reflect.ValueOf(user)
reflectedStringValue := reflect.ValueOf(aString)
fmt.Println(reflectedUserValue.Interface())
fmt.Println(reflectedStringValue.Interface())
fmt.Println("-------------------------------------")
//getting the reflect pointers to be able to modify the values
reflUserPtr := reflect.ValueOf(&user)
reflStrinPtr := reflect.ValueOf(&aString)
secondUser := User{ID: 54, Email: "new@value.com"}
secondUserValue := reflect.ValueOf(secondUser)
reflUserPtr.Elem().Set(secondUserValue)
reflStrinPtr.Elem().SetString("Updated value")
// values are modified
fmt.Println(user)
fmt.Println(aString)
fmt.Println("-------------------------------------")
// creating a new User instance using reflection
rType := reflect.TypeOf(user)
newUserValue := reflect.New(rType)
newUserValue.Elem().Field(0).SetInt(66)
newUserValue.Elem().Field(1).SetString("iamnew@example.com")
// cast the reflected value to the User type
newUser := newUserValue.Interface().(*User)
fmt.Println("New user fields: ", newUser.ID, newUser.Email)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment