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类型是一样的,但是我们可以实现很多种的逻辑,这样使得我们的程序变得非常的灵活。

  • 相关阅读:
    64最长和谐子序列(594)
    63找到字符串中所有字母异位词(438)
    62有效的数独(36)
    10.10
    9.27作业
    9.27
    9.26
    9.25
    9.18学习内容
    9.17作业
  • 原文地址:https://www.cnblogs.com/junneyang/p/6077118.html
Copyright © 2011-2022 走看看