You have to use a temporary to swap the values:

tmp := a.Interface()
a.Set(b)
b.Set(reflect.ValueOf(tmp))


----
*Josh Humphries*
jh...@bluegosling.com

On Mon, Jul 31, 2017 at 10:18 AM, 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.

Reply via email to