Although that solution creates a heap-allocated tmp for every element in the slice. Using an interface, the value will be inlined instead of heap-allocated if it fits without boxing (so most primitive types and pointer types won't need heap allocation).
---- *Josh Humphries* jh...@bluegosling.com On Tue, Aug 1, 2017 at 7:29 AM, roger peppe <rogpe...@gmail.com> wrote: > FWIW, you don't have to use Interface to do the swap: > > https://play.golang.org/p/O8lGJGGOXP > > On 31 July 2017 at 15:18, eZio Pan <eziopa...@gmail.com> wrote: > > Hello, > > I want to build a "universal slice reverser" with reflect.MakeFunc. But I > > don't know how to get a copy of reflect.Value's underlying value, which > make > > result not correct. > > > > Here is the code: > > > > package main > > > > import ( > > "fmt" > > "reflect" > > ) > > > > func reverse(in []reflect.Value) (out []reflect.Value) { > > inls := in[0] > > inlslen := inls.Len() > > > > for i, j := 0, inlslen-1; i < j; i, j = i+1, j-1 { > > a := inls.Index(i) > > b := inls.Index(j) > > // how to get underlying value of a and b ? > > a.Set(b) > > b.Set(a) > > } > > return in > > } > > > > var intFlipper func([]int) []int > > > > func main() { > > emptyFunc := reflect.ValueOf(&intFlipper).Elem() > > pseudoFunc := reflect.MakeFunc(emptyFunc.Type(), reverse) > > emptyFunc.Set(pseudoFunc) > > fmt.Printf("%v\n", intFlipper([]int{2, 3, 4, 5, 6, 7})) > > } > > > > My code return [7 6 5 5 6 7], but excepting result is [7 6 5 4 3 2] > > > > -- > > You received this message because you are subscribed to the Google Groups > > "golang-nuts" group. > > To unsubscribe from this group and stop receiving emails from it, send an > > email to golang-nuts+unsubscr...@googlegroups.com. > > For more options, visit https://groups.google.com/d/optout. > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.