Last active
August 29, 2015 14:18
-
-
Save drewwells/b8577ed61c0ec983a105 to your computer and use it in GitHub Desktop.
Examples of reflection with slices
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
func copySlice(dst interface{}, src interface{}) error { | |
d := reflect.ValueOf(dst) | |
if !d.CanAddr() { | |
d = d.Elem() | |
} else { | |
return errors.New("dst must be pointer") | |
} | |
s := reflect.ValueOf(src) | |
c := reflect.MakeSlice(d.Type(), s.Len(), s.Len()) | |
reflect.Copy(c, s) | |
d.Set(c) | |
return nil | |
} | |
func copyBytes(dst *[]byte, src []byte) error { | |
r := reflect.ValueOf(dst).Elem() | |
if !r.CanSet() { | |
return errors.New("Value unsettable") | |
} | |
r.SetBytes(src) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment