Skip to content

Instantly share code, notes, and snippets.

@bokwoon95
Last active November 4, 2022 23:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bokwoon95/3fe821a5218db6f64a5f13f508ab9564 to your computer and use it in GitHub Desktop.
Save bokwoon95/3fe821a5218db6f64a5f13f508ab9564 to your computer and use it in GitHub Desktop.
Go Generics type signature for ensuring argument is a pointer
// https://go.dev/play/p/BT-OUMK5Rtp
package main
import (
"fmt"
)
// Deref will dereference a generic pointer.
// It will fail at compile time if pt is not a pointer.
// This is useful for functions that require pointers to structs and not structs directly.
func Deref[T any](ptr *T) T {
return *ptr
}
func main() {
var test = "test"
var num = 1
a, b, c := &test, &num, &[]float64{2.0}
A, B, C := Deref(a), Deref(b), Deref(c)
fmt.Printf("%#v, %#v, %#v\n", A, B, C)
// Deref(C) // this will fail at compile time because C is not a pointer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment