Created
April 26, 2022 15:11
-
-
Save jamesrr39/0eaf59e2b2e85ba789576660961aad53 to your computer and use it in GitHub Desktop.
Go - reflection example
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 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