Skip to content

Instantly share code, notes, and snippets.

@jamesrr39
Created April 26, 2022 15:11
Show Gist options
  • Save jamesrr39/0eaf59e2b2e85ba789576660961aad53 to your computer and use it in GitHub Desktop.
Save jamesrr39/0eaf59e2b2e85ba789576660961aad53 to your computer and use it in GitHub Desktop.
Go - reflection example
package main
import (
"fmt"
"reflect"
)
type Date struct {
Day int
Month int
Year int
}
type Person struct {
Name string
DOB Date
}
func main() {
changeName()
changeDateOfBirth()
}
func changeName() {
person := Person{}
rvName := reflect.ValueOf(&person.Name)
printTypeAndSettability(rvName)
rvName.Elem().SetString("test user")
fmt.Println(person.Name)
}
func changeDateOfBirth() {
person := Person{}
rvDOB := reflect.New(
reflect.Indirect(
reflect.ValueOf(reflect.ValueOf(person).FieldByName("DOB").Interface()),
).Type(),
)
printTypeAndSettability(rvDOB)
newDate := Date{Day: 20, Month: 12, Year: 1980}
rvDOB.Elem().Set(reflect.ValueOf(newDate))
reflect.ValueOf(&person.DOB).Elem().Set(rvDOB.Elem())
fmt.Printf("%v, %v\n", rvDOB.Elem().Interface(), person.DOB)
}
func printTypeAndSettability(thing reflect.Value) {
fmt.Printf("type: %s, canSet: as pointer? %v, Elem()? %v\n", thing.Type().String(), thing.CanSet(), thing.Elem().CanSet())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment