如何在 Go 中创建一个变量类型的切片?

我有一个功能。


func doSome(v interface{}) {


}  

如果我通过指针将结构切片传递给函数,则函数必须填充切片。


type Color struct {

}

type Brush struct {

}


var c []Color

doSome(&c) // after с is array contains 3 elements type Color


var b []Brush

doSome(&b) // after b is array contains 3 elements type Brush

也许我需要使用反射,但是如何?


侃侃无极
浏览 159回答 3
3回答

MM们

func doSome(v interface{}) {    s := reflect.TypeOf(v).Elem()    slice := reflect.MakeSlice(s, 3, 3)    reflect.ValueOf(v).Elem().Set(slice)}  

杨魅力

类型开关!!package mainimport "fmt"func doSome(v interface{}) {  switch v := v.(type) {  case *[]Color:    *v = []Color{Color{0}, Color{128}, Color{255}}  case *[]Brush:    *v = []Brush{Brush{true}, Brush{true}, Brush{false}}  default:    panic("unsupported doSome input")  }}  type Color struct {    r uint8}type Brush struct {    round bool}func main(){    var c []Color    doSome(&c) // after с is array contains 3 elements type Color    var b []Brush    doSome(&b) // after b is array contains 3 elements type Brush    fmt.Println(b)    fmt.Println(c)}

忽然笑

Go 没有泛型。你的可能性是:接口调度type CanTraverse interface {&nbsp; &nbsp; Get(int) interface{}&nbsp; &nbsp; Len() int}type Colours []Colourfunc (c Colours) Get(i int) interface{} {&nbsp; &nbsp; return c[i]}func (c Colours) Len() int {&nbsp; &nbsp; return len(c)}func doSome(v CanTraverse) {&nbsp; &nbsp; for i := 0; i < v.Len; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(v.Get(i))&nbsp; &nbsp; }}按照@Plato 的建议输入 switchfunc doSome(v interface{}) {&nbsp; switch v := v.(type) {&nbsp; case *[]Colour:&nbsp; &nbsp; //Do something with colours&nbsp; case *[]Brush:&nbsp; &nbsp; //Do something with brushes&nbsp; default:&nbsp; &nbsp; panic("unsupported doSome input")&nbsp; }}像 fmt.Println() 一样进行反射。反射非常强大但非常昂贵,代码可能很慢。最小的例子func doSome(v interface{}) {&nbsp; &nbsp; value := reflect.ValueOf(v)&nbsp; &nbsp; if value.Kind() == reflect.Slice {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < value.Len(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; element := value.Slice(i, i+1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(element)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("It's not a slice")&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go