golang裏要實現查找數組最小數的泛型函數,須要用到類型開關。
golang
gol的類型開關寫法:數組
switch v.(type) { case int: case float64: case string: }
思路就是遍歷數組,遇到更小的數保存下來,函數退出返回那個數。函數
golang代碼:spa
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:rest
#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; }