Created
July 20, 2019 07:11
-
-
Save fengyfei/b7c794963140933613ad7bdbc102a2c1 to your computer and use it in GitHub Desktop.
[Go][Reflect] Enforce Pointer & CanSet
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 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