Last active
January 13, 2023 00:00
-
-
Save mdwhatcott/de2dbfaed481c703557440209117d896 to your computer and use it in GitHub Desktop.
Go is stringly typed, right?
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 ( | |
MyFirstEvent struct{ AccountID uint64 } | |
MySecondEvent struct{ AccountID uint64 } | |
) | |
func main() { | |
first := MyFirstEvent{AccountID: 123} | |
second := MySecondEvent{AccountID: 456} | |
var ( | |
firstID uint64 = RuntimeGet[uint64](first, "AccountID") | |
secondID uint64 = RuntimeGet[uint64](second, "AccountID") | |
) | |
fmt.Println(firstID, secondID) // 123 456 | |
RuntimeGet[uint64](first, "Unsafe") // panic: reflect: call of reflect.Value.Interface on zero Value | |
} | |
func RuntimeGet[T any](v any, field string) T { | |
return reflect.ValueOf(v).FieldByName(field).Interface().(T) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment