怎么样通过反射reflect向slice追加元素或让这个slice指向另外一个slice

anlitylee · 2019-06-07 18:30:25 · 1306 次点击
package main

import ( 
    "fmt" 
)

type User struct {
    Id int
    Name string
}

func ChangeSlice(s interface{}) {
    user1 := User{
        Id: 1,
        Name: "张三",
    }
    newSlice := make([]User, 0)
    newSlice = append(newSlice, user1)
    *(s.(*[]User)) = newSlice
}

func main() {
    users := make([]User, 0)
    ChangeSlice(&users)
    // 这里希望让Users指向ChangeSlice函数中的那个新数组
    fmt.Println(users)  // 希望输出[{1  张三}],但是现在输出[]
}
#1
更多评论

非常感谢,你的代码没有问题,确实可行!可能是我没有表述清楚,实际上我是想通过反射的方式,而不是断言! 通过搜索,我找到了一个解决方案

package main

import (
    "fmt"
    "reflect"
    "os"
)

type User struct {
    Id int
    Name string
}

func ChangeSlice(s interface{}) {
    sT := reflect.TypeOf(s)
    if sT.Kind() != reflect.Ptr {
        fmt.Println("参数必须是ptr类型")
        os.Exit(-1)
    }
    sV := reflect.ValueOf(s)
    // 取得数组中元素的类型
    sEE := sT.Elem().Elem()
    // 数组的值
    sVE := sV.Elem()

    // new一个数组中的元素对象
    sON := reflect.New(sEE)
    // 对象的值
    sONE := sON.Elem()
    // 给对象复制
    sONEId := sONE.FieldByName("Id")
    sONEName := sONE.FieldByName("Name")
    sONEId.SetInt(10)
    sONEName.SetString("李四")

    // 创建一个新数组并把元素的值追加进去
    newArr := make([]reflect.Value, 0)
    newArr = append(newArr, sON.Elem())

    // 把原数组的值和新的数组合并
    resArr := reflect.Append(sVE, newArr...)

    // 最终结果给原数组
    sVE.Set(resArr)
}

func main() {
    users := make([]User, 0)
    ChangeSlice(&users)
    // 这里希望让Users指向ChangeSlice函数中的那个新数组
    fmt.Println(users)
}
#2