golang里要实现查找数组最小数的泛型函数,需要用到类型开关。
gol的类型开关写法:
switchv.(type){ caseint: casefloat64: casestring: }
思路就是遍历数组,遇到更小的数保存下来,函数退出返回那个数。
golang代码:
packagemain import( "fmt" ) funcMinimum(firstinterface{},rest...interface{})interface{}{ minimum:=first for_,v:=rangerest{ switchv.(type){ caseint: ifv:=v.(int);v<minimum.(int){ minimum=v } casefloat64: ifv:=v.(float64);v<minimum.(float64){ minimum=v } casestring: ifv:=v.(string);v<minimum.(string){ minimum=v } } } returnminimum } funcmain(){ i:=Minimum(1,3,5,7,9,10,-1,1).(int) fmt.Printf("i=%d\n",i) }
clang:
#include<stdio.h> intmin_int(void*v1,void*v2){ return*(int*)v1>*(int*)v2; } intmin_double(void*v1,void*v2){ return*(double*)v1>*(double*)v2; } void*minimum(void*base,intsize,intesize,int(*min_cmp)(void*,void*)){ inti; void*mini=base; for(i=1;i<size;i++){ if(min_cmp(mini,base+i*esize)) mini=base+i*esize; } returnmini; } #defineARR_LEN(arr)sizeof(arr)/sizeof((arr)[0]) #defineARR_ESIZE(arr)sizeof((arr)[0]) intmain(){ void*min; intarr_int[]={0,6,8,2}; min=minimum(arr_int,ARR_LEN(arr_int),ARR_ESIZE(arr_int),min_int); printf("%d\n",*(int*)min); doublearr_double[]={1.1,2.2,3.3,4.4,5.5,6.6,-3.14,99}; min=minimum(arr_double,ARR_LEN(arr_double),ARR_ESIZE(arr_double),min_double); printf("%lf\n",*(double*)min); return0; }原文链接:https://www.f2er.com/go/190387.html