Skip to content

Instantly share code, notes, and snippets.

@mkfsn
Created December 26, 2021 09:19
Show Gist options
  • Save mkfsn/517058d8edbebc56e36085b965e3f555 to your computer and use it in GitHub Desktop.
Save mkfsn/517058d8edbebc56e36085b965e3f555 to your computer and use it in GitHub Desktop.
Go Generics Reference function to any type
// https://go.dev/play/p/Yrwl1kVfvXi?v=gotip
package main
import (
"fmt"
"time"
)
type Ptr[T any] interface {
*T
}
// Ref returns the reference of T.
//
// Or this also works:
// func Ref[T any](t T) *T {
// return &t
// }
func Ref[T any, PtrT Ptr[T]](t T) PtrT {
return &t
}
func PrintPtr[T any, PtrT Ptr[T]](ptr PtrT) {
fmt.Printf("%T: v=%p *v=%v\n", ptr, ptr, *ptr)
}
type Point struct {
x, y float64
}
func main() {
PrintPtr(Ref(42))
PrintPtr(Ref(59.3))
PrintPtr(Ref("Hello World"))
PrintPtr(Ref(time.Now()))
PrintPtr(Ref(Point{3.0, 4.0}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment