Skip to content

Instantly share code, notes, and snippets.

@MaximeWeyl
Last active December 17, 2020 04:09
Show Gist options
  • Save MaximeWeyl/ef368af8a1c44ad6504bc24fae8442a3 to your computer and use it in GitHub Desktop.
Save MaximeWeyl/ef368af8a1c44ad6504bc24fae8442a3 to your computer and use it in GitHub Desktop.
Golang one liner to create a pointer to a new (non zero) value
package newPointer
import "reflect"
// Just do not forget to cast it back
// Example :
// var a := getNewPointerForValue(int32(12)).(*int32)
// Uses reflection.
// Slower, but who cares. Postgres and network are the real bottleneck.
func GetNewPointerForValue(value interface{}) interface{} {
p := reflect.New(reflect.TypeOf(value))
p.Elem().Set(reflect.ValueOf(value))
return p.Interface()
}
@MaximeWeyl
Copy link
Author

Do not use if performance is a real requirement.
If not (as often), it may be good for readability to use this one liner.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment