【发布时间】:2019-01-08 18:02:28
【问题描述】:
我正在开发一个特定 API 的客户端,并且我构建了多个结构(每个路由一个结构)。
API 适用于页面,因此我有 getter 返回结构的切片。这是通过一个通用函数完成的,该函数接受一个接口,该接口应该是指向所需结构切片的指针,因此我可以使用 json 包中的 Unmarshal。
我面临的问题是我想在一个请求中获取所有页面,但为了做到这一点,我需要连接几个切片。
我尝试使用reflect 执行此操作,但我只能设法创建一个新切片,而不会实际更改我的接口指向的值。
这是我的代码的一部分:
func concatenateSlice(dst, src interface{})(){
dstValue := reflect.ValueOf(dst)
srcValue := reflect.ValueOf(src)
if srcValue.Type() != dstValue.Type(){
return
}
switch srcValue.Kind(){
case reflect.Ptr, reflect.Slice:
dstValuePoint := reflect.Indirect(dstValue)
srcValuePoint := reflect.Indirect(srcValue)
reflect.Copy(dstValuePoint, reflect.AppendSlice(dstValuePoint, srcValuePoint))
}
}
对于这个草率的帖子,我很抱歉,这是我第一次使用 stackoverflow。
【问题讨论】:
标签: pointers go reflection slice