Last active
November 4, 2022 23:11
-
-
Save bokwoon95/3fe821a5218db6f64a5f13f508ab9564 to your computer and use it in GitHub Desktop.
Go Generics type signature for ensuring argument is a pointer
This file contains hidden or 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
// 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