• go 函数也是一种类型, 匿名函数


    /* 函数也是一种类型 */
    package main
    
    import (
    	"fmt"
    )
    
    /* 自定义函数类型 接受两个int参数,返回int类型*/
    type op_func func(int, int) int
    
    func main() {
    	test_func()
    }
    
    func test_func() {
    	/* 声明变量c 类型为自定义类型 */
    	var c op_func
    	/* add函数赋值给c add函数接受两个int参数,返回int类型 */
    	c = add
    	sum := c(100, 103)
    	fmt.Println(sum)
    
    	/* 调用自定义函数,传递c变量 */
    	sum = op(c, 100, 130)
    	fmt.Println(sum)
    
    	/* 调用自定义函数,传递sub函数 */
    	sum = op(sub, 200, 100)
    	fmt.Println(sum)
    
    	// sum = op(sub1, 100, 200) //编译报错,sub1函数接受三个参数,不符合自定义类型
    
    	/* 声明并调用匿名函数 */
    	result := func(a, b int) int {
    		return a + b
    	}(100, 200)
    	fmt.Println("匿名函数100+200=", result)
    
    }
    
    func add(a, b int) int {
    	return a + b
    }
    
    func sub(a int, b int) int {
    	return a - b
    }
    func sub1(a, b, c int) int {
    	return c - b - a
    }
    
    /* 自定义op函数,接受自定义类型参数 两个int类型 */
    func op(op op_func, a, b int) int {
    	return op(a, b)
    }
    

    输出:

    203
    230
    100
    匿名函数100+200= 300
    
  • 相关阅读:
    端口以及服务常用cmd
    异步,同步,阻塞,非阻塞,并行,并发,
    mysql启动不起来
    安装nagios出现的错误
    Linux内核优化
    mysql使用常见问题
    mysql日志
    mysql数据库使用脚本实现分库备份过程
    mysqladmin常用用法
    mysql授权
  • 原文地址:https://www.cnblogs.com/heris/p/16210588.html
Copyright © 2020-2023  润新知