funcmain(){ findAnyMax([]int{2,1,3,5,7,6,4}) } funcfindAnyMax(i[]interface{})interface{}{ switchi.(type){ casestring: //... caseint: //... } return/*...*/ }
运行会失败:cannot use i (type[]int) as type []interface in function argument
修改了一下,实际上通过规避slice的转换同样没有根本性的解决问题,golang中不容许slice的隐式转换。
packagemain import( "fmt" ) funcmain(){ fmt.Println(findAnyMax(Int{2,2,8,100,12,34})) fmt.Println(findAnyMax(Float{1,4,102,100})) } typeInt[]int typeFloat[]float32 typeMaxinterface{ Len()int Get(iint)interface{} } func(iInt)Len()int{ returnlen(i) } func(iInt)Get(idxint)interface{}{ returni[idx] } func(iFloat)Len()int{ returnlen(i) } func(iFloat)Get(idxint)interface{}{ returni[idx] } funcfindAnyMax(lMax)interface{}{ switchl.(type){ caseInt: max:=l.Get(0) fori:=1;i<l.Len();i++{ ifl.Get(i).(int)>max.(int){ max=l.Get(i) } } returnmax caseFloat: max:=l.Get(0) fori:=1;i<l.Len();i++{ ifl.Get(i).(float32)>max.(float32){ max=l.Get(i) } } returnmax default: fmt.Println("typemiss") } returnnil }
有点费解~~~