zoukankan      html  css  js  c++  java
  • 【GoLang】函数作为 类型 和 值

    代码示例

    package test
    
    import (
        "fmt"
        "testing"
    )
    
    type testInt func(int) bool
    
    func isOdd(integer int) bool {
        if integer%2 == 0 {
            return false
        }
        return true
    }
    
    func isEven(integer int) bool {
        if integer%2 == 0 {
            return true
        }
        return false
    }
    
    func filter(slice []int, f testInt) []int {
        var result []int
        for _, value := range slice {
            if f(value) {
                result = append(result, value)
            }
        }
        return result
    }
    
    func Test_Func(t *testing.T) {
        slice := []int{1, 2, 3, 4, 5, 7}
        fmt.Println("slice = ", slice)
        odd := filter(slice, isOdd)
        fmt.Println("Odd elements of slice are: ", odd)
        even := filter(slice, isEven)
        fmt.Println("Even elements of slice are: ", even)
    }

    输出结果:

    slice =  [1 2 3 4 5 7]
    Odd elements of slice are:  [1 3 5 7]
    Even elements of slice are:  [2 4]

    函数当做值和类型在我们写一些通用接口的时候非常有用,通过上面例子我们看到testInt这个类型是一个函数类型,然后两个filter函数的参数和返回值与testInt类型是一样的,但是我们可以实现很多种的逻辑,这样使得我们的程序变得非常的灵活。

  • 相关阅读:
    160-13. 罗马数字转整数
    159-118. 杨辉三角
    158-190. 颠倒二进制位
    157-461. 汉明距离
    156-412. Fizz Buzz
    155-278. 第一个错误的版本
    154-108. 将有序数组转换为二叉搜索树
    153-101. 对称二叉树
    152-234. 回文链表
    秒杀程序架构演进
  • 原文地址:https://www.cnblogs.com/junneyang/p/6077118.html
Copyright © 2011-2022 走看看