Skip to content

Instantly share code, notes, and snippets.

@fengyfei
Created July 20, 2019 07:11
Show Gist options
  • Save fengyfei/b7c794963140933613ad7bdbc102a2c1 to your computer and use it in GitHub Desktop.
Save fengyfei/b7c794963140933613ad7bdbc102a2c1 to your computer and use it in GitHub Desktop.
[Go][Reflect] Enforce Pointer & CanSet
package main
import (
"fmt"
"reflect"
)
func EnforcePtr(obj interface{}) (reflect.Value, error) {
v := reflect.ValueOf(obj)
if v.Kind() != reflect.Ptr {
if v.Kind() == reflect.Invalid {
return reflect.Value{}, fmt.Errorf("expected pointer, but got invalid kind")
}
return reflect.Value{}, fmt.Errorf("expected pointer, but got %v type", v.Type())
}
if v.IsNil() {
return reflect.Value{}, fmt.Errorf("expected pointer, but got nil")
}
return v.Elem(), nil
}
func canSet(a interface{}) {
v, err := EnforcePtr(a)
if err != nil {
panic(err)
}
if v.CanSet() {
fmt.Println(v.Kind(), " can set")
} else {
fmt.Println(v.Kind(), " can't set")
}
}
func main() {
i := 0
canSet(&i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment