5

からスライスを作成しようとしていますreflect.Type。これは私がこれまでに持っているものです。

package main

import (
    "fmt"
    "reflect"
)

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})

    elemSlice := reflect.New(reflect.SliceOf(elemType)).Interface()

    elemSlice = append(elemSlice, TestStruct{"Testing"})

    fmt.Printf("%+v\n", elemSlice)

}

ただし、次のエラーが発生し、への変換をハードコーディングせずに回避する方法がわかりません[]TestStruct

prog.go:17: first argument to append must be slice; have interface {}

interface{}からへの変換をハードコードすることなく、返されたインターフェイスをスライスとして扱う方法はあります[]TestStructか?

4

2 に答える 2

14

いいえ、あなたの説明は不可能です。.Interface()あなたができることを制限する結果をアサートするタイプではありません。reflect.Valueあなたの最善のチャンスは、値で作業を続けることです:

package main

import (
    "fmt"
    "reflect"
)

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})

    elemSlice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)

    elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))

    fmt.Printf("%+v\n", elemSlice)

}

https://play.golang.org/p/WkGPjv0m_P

于 2016-08-07T22:23:51.770 に答える
5

1- と を使用reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)して
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}]
}
于 2016-08-07T22:24:18.370 に答える