Skip to content

Instantly share code, notes, and snippets.

@fengyfei
Created July 20, 2019 07:27
Show Gist options
  • Save fengyfei/3db052ec84be83722ccd6cf88d232a3a to your computer and use it in GitHub Desktop.
Save fengyfei/3db052ec84be83722ccd6cf88d232a3a to your computer and use it in GitHub Desktop.
[Go][Reflect] AssignableTo & ConveribleTo
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 main() {
i := 1
f := 0.0
pi, _ := EnforcePtr(&i)
pf, _ := EnforcePtr(&f)
ti := pi.Type()
tf := pf.Type()
if ti.AssignableTo(tf) {
pf.Set(pi)
goto finish
} else {
fmt.Println("Condition I: ", ti.Name(), " can not assign to ", tf.Name())
}
if ti.ConvertibleTo(tf) {
pf.Set(pi.Convert(tf))
goto finish
} else {
fmt.Println("Condition II: ", ti.Name(), " can not assign to ", tf.Name())
}
finish:
fmt.Println(i, f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment