Skip to content

Instantly share code, notes, and snippets.

@chai2010
Created October 17, 2014 05:32
Show Gist options
  • Select an option

  • Save chai2010/350df12e19220fdbd014 to your computer and use it in GitHub Desktop.

Select an option

Save chai2010/350df12e19220fdbd014 to your computer and use it in GitHub Desktop.
[]T转[]*T类型
// http://play.golang.org/p/068n_JHmQU
package main
import (
"fmt"
"image"
"reflect"
)
func main() {
v0 := []image.Point{
image.Point{X: 1, Y: 101},
image.Point{X: 2, Y: 202},
}
fmt.Printf("%T, %v\n", v0, v0)
v1 := MapSliceToPtr(v0)
fmt.Printf("%T, %v\n", v1, v1)
}
func MapSliceToPtr(slice interface{}) interface{} {
val := reflect.ValueOf(slice)
if val.Kind() != reflect.Slice {
panic(fmt.Sprintf("MapSlice called with non-slice value of type %T", slice))
}
out := reflect.MakeSlice(
reflect.SliceOf(reflect.PtrTo(reflect.TypeOf(slice).Elem())),
val.Len(),
val.Cap(),
)
for i := 0; i < val.Len(); i++ {
v := reflect.New(reflect.TypeOf(slice).Elem())
v.Elem().Set(val.Index(i))
out.Index(i).Set(v)
}
return out.Interface()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment