Skip to content

Instantly share code, notes, and snippets.

@SoulSu
Created November 27, 2018 10:10
Show Gist options
  • Save SoulSu/7825147f4924afd727bb7ba89fb952f8 to your computer and use it in GitHub Desktop.
Save SoulSu/7825147f4924afd727bb7ba89fb952f8 to your computer and use it in GitHub Desktop.
Golang 实现一个接口后 方法需要传数组怎么办
package main
import (
"fmt"
"reflect"
)
type Aer interface {
GetVal() string
SetVal(int)
}
type AA struct {
A int
}
func (a *AA) GetVal() string {
return fmt.Sprintf("%v", a.A)
}
func (a *AA) SetVal(i int) {
a.A += i
}
func arrAer(al []Aer) {
for k, v := range al {
fmt.Printf("k=>%v v=>%v vv=>%v\n", k, v, v.GetVal())
}
}
func aer(al Aer) {
fmt.Printf("k=>%v v=>%v vv=>%v\n", al, al, al.GetVal())
}
func ToAer(i interface{}) []Aer {
ua := make([]Aer, 0)
rv := reflect.ValueOf(i)
if rv.Kind() != reflect.Slice {
panic("not support type")
}
l := rv.Len()
for i := 0; i < l; i++ {
iv, ok := rv.Index(i).Interface().(Aer)
if !ok {
panic("not support type sub index")
}
ua = append(ua, iv)
}
for _, v := range ua {
v.SetVal(4)
}
return ua
}
func main() {
al := make([]*AA, 0)
al = append(al, &AA{A: 1})
al = append(al, &AA{A: 2})
al = append(al, &AA{A: 3})
nal := ToAer(al)
fmt.Println(al, nal)
arrAer(nal)
aer(al[0])
aer(al[1])
aer(al[2])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment