Skip to content

Instantly share code, notes, and snippets.

@nicolasparada
Created June 22, 2022 23:18
Show Gist options
  • Save nicolasparada/55fbed59b0536eaae4a1143765749772 to your computer and use it in GitHub Desktop.
Save nicolasparada/55fbed59b0536eaae4a1143765749772 to your computer and use it in GitHub Desktop.
generic shared data
package main
import (
"fmt"
"reflect"
)
func main() {
render(MyData{Foo: "bar"})
}
type MyData struct {
Shared
Foo string
}
func render[T any](data T) {
if val := reflect.ValueOf(&data); val.IsValid() && val.Kind() == reflect.Pointer {
fmt.Println("&data is pointer")
if val := val.Elem(); val.IsValid() && val.Kind() == reflect.Struct {
fmt.Println("data is struct")
if val := val.FieldByName("Shared"); val.IsValid() && val.CanSet() && val.Type() == reflect.TypeOf(Shared{}) {
fmt.Println("data has shared data")
val.Set(reflect.ValueOf(Shared{
Authenticated: true,
User: User{
ID: "1",
Email: "[email protected]",
Username: "user",
},
}))
}
}
}
fmt.Printf("data: %+v\n", data)
// Output: data: {Shared:{Authenticated:true User:{ID:1 Email:[email protected] Username:user}} Foo:bar}
}
type Shared struct {
Authenticated bool
User User
}
type User struct {
ID string
Email string
Username string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment