Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Last active January 13, 2023 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/de2dbfaed481c703557440209117d896 to your computer and use it in GitHub Desktop.
Save mdwhatcott/de2dbfaed481c703557440209117d896 to your computer and use it in GitHub Desktop.
Go is stringly typed, right?
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