Last active
December 17, 2020 04:09
-
-
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
This file contains 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 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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do not use if performance is a real requirement.
If not (as often), it may be good for readability to use this one liner.