1-使用reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)
and
reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
,
就像这个工作示例代码:
package main
import "fmt"
import "reflect"
func main() {
elemType := reflect.TypeOf(TestStruct{})
elemSlice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)
elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
fmt.Println(elemSlice) // [{Testing}]
}
type TestStruct struct {
TestStr string
}
2-使用reflect.New(reflect.SliceOf(elemType)).Elem()
和
elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
喜欢这个工作示例代码:
package main
import "fmt"
import "reflect"
type TestStruct struct {
TestStr string
}
func main() {
elemType := reflect.TypeOf(TestStruct{})
elemSlice := reflect.New(reflect.SliceOf(elemType)).Elem()
elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
fmt.Printf("%+v\n", elemSlice) // [{TestStr:Testing}]
fmt.Println(elemSlice) // [{Testing}]
}
输出:
[{TestStr:Testing}]
[{Testing}]
3-如果您需要append
,唯一的方法是使用s := elemSlice.([]TestStruct)
,就像这个工作示例代码:
package main
import "fmt"
import "reflect"
type TestStruct struct {
TestStr string
}
func main() {
elemType := reflect.TypeOf(TestStruct{})
elemSlice := reflect.New(reflect.SliceOf(elemType)).Elem().Interface()
s := elemSlice.([]TestStruct)
s = append(s, TestStruct{"Testing"})
fmt.Printf("%+v\n", elemSlice) // []
fmt.Println(s) // [{Testing}]
}