求问下面的Add2这里怎么实现?sum为interface好像没法任意求和?funcAdd(vars...int)(retint){varsumintfor_,v:=rangevars{//fmt.Println("v",v)sum+=v}returnsum}//这里怎么实现?sum为interface好像没法任意求和?funcAdd2(vars...interface{})(retinterface{}){/*varsuminterface{}for_,v:=rangevars{switchv.(type){caseint:sum+=vcasefloat64:sum+=vcasestring:sum+=v}}*/returnsum}funcmain(){fmt.Println(Add2(1,2))fmt.Println(Add2(1,2,3))fmt.Println(Add2(2.4,3.6,1.0))fmt.Println(Add2("Hello","world","zhong"))}
2 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
你想要的是泛型吧?凑合写了一个,忽略与第一个参数不同类型的值。funcadd(vars...interface{})(retinterface{}){varsuminterface{}for_,v:=rangevars{sum=addTo(sum,v)}returnsum}funcaddTo(suminterface{},vinterface{})(retinterface{}){if(sum==nil){returnv}switchv.(type){caseint:ifintSum,found:=sum.(int);found{returnintSum+v.(int)}casestring:ifstrSum,found:=sum.(string);found{returnstrSum+v.(string)}}returnsum}
添加回答
举报
0/150
提交
取消