Last active
January 17, 2024 00:58
-
-
Save bkono/8f832566e6c2875d7cede15e46aa9d58 to your computer and use it in GitHub Desktop.
A decent use of generics, safe derefence
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
// Package ptr implements a simple pointer instrumentation. | |
// As it is based on Go generics, the minimal Go version is 1.18. | |
// Credit to https://github.com/candiduslynx/ptr/ and https://gist.github.com/bkono/8f832566e6c2875d7cede15e46aa9d58 | |
package ptr | |
// Deref will deref the pointer if it can, otherwise it will return either a fallback if provided, or a default value for T | |
func Deref[T any](pointer *T, fallback ...T) T { | |
if pointer != nil { | |
return *pointer | |
} | |
var result T | |
if len(fallback) > 0 { | |
result = fallback[0] | |
} | |
return result | |
} | |
// Ref will return a pointer to the value. | |
func Ref[T any](value T) (pointer *T) { return &value } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment