golang里要实现查找数组最小数的泛型函数,需要用到类型开关。
gol的类型开关写法:
switch v.(type) { case int: case float64: case string: }
思路就是遍历数组,遇到更小的数保存下来,函数退出返回那个数。
golang代码:
package main import ( "fmt" ) func Minimum(first interface{}, rest ...interface{}) interface{}{ minimum := first for _, v := range rest { switch v.(type) { case int: if v := v.(int); v < minimum.(int) { minimum = v } case float64: if v := v.(float64); v < minimum.(float64) { minimum = v } case string: if v := v.(string); v < minimum.(string) { minimum = v } } } return minimum } func main() { i := Minimum(1, 3, 5, 7, 9, 10, -1, 1).(int) fmt.Printf("i = %d\n", i) }
clang:
#include <stdio.h> int min_int(void *v1, void *v2) { return *(int *)v1 > *(int *)v2; } int min_double(void *v1, void *v2) { return *(double *)v1 > *(double *)v2; } void *minimum(void *base, int size, int esize, int (*min_cmp)(void *, void *)) { int i; void *mini = base; for (i = 1; i < size; i++) { if (min_cmp(mini, base + i * esize)) mini = base + i * esize; } return mini; } #define ARR_LEN(arr) sizeof(arr) / sizeof((arr)[0]) #define ARR_ESIZE(arr) sizeof((arr)[0]) int main() { void *min; int arr_int[] = {0, 5, 6, 7, 8, 9, -1, 2}; min = minimum(arr_int, ARR_LEN(arr_int), ARR_ESIZE(arr_int), min_int); printf("%d\n", *(int *)min); double arr_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); return 0; }
有疑问加站长微信联系(非本文作者)