3 回答
TA贡献1886条经验 获得超2个赞
func doSome(v interface{}) {
s := reflect.TypeOf(v).Elem()
slice := reflect.MakeSlice(s, 3, 3)
reflect.ValueOf(v).Elem().Set(slice)
}
TA贡献1811条经验 获得超6个赞
类型开关!!
package main
import "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)
}
TA贡献1806条经验 获得超5个赞
Go 没有泛型。你的可能性是:
接口调度
type CanTraverse interface {
Get(int) interface{}
Len() int
}
type Colours []Colour
func (c Colours) Get(i int) interface{} {
return c[i]
}
func (c Colours) Len() int {
return len(c)
}
func doSome(v CanTraverse) {
for i := 0; i < v.Len; i++ {
fmt.Println(v.Get(i))
}
}
按照@Plato 的建议输入 switch
func doSome(v interface{}) {
switch v := v.(type) {
case *[]Colour:
//Do something with colours
case *[]Brush:
//Do something with brushes
default:
panic("unsupported doSome input")
}
}
像 fmt.Println() 一样进行反射。反射非常强大但非常昂贵,代码可能很慢。最小的例子
func doSome(v interface{}) {
value := reflect.ValueOf(v)
if value.Kind() == reflect.Slice {
for i := 0; i < value.Len(); i++ {
element := value.Slice(i, i+1)
fmt.Println(element)
}
} else {
fmt.Println("It's not a slice")
}
}
- 3 回答
- 0 关注
- 158 浏览
添加回答
举报