Skip to content

Instantly share code, notes, and snippets.

@drewwells
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewwells/b8577ed61c0ec983a105 to your computer and use it in GitHub Desktop.
Save drewwells/b8577ed61c0ec983a105 to your computer and use it in GitHub Desktop.
Examples of reflection with slices
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