IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

四十一、Go 语言 – 闭包函数

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

文章永久连接:https://tech.souyunku.com/?p=5358

Go 语言支持闭包函数,又称匿名函数

匿名函数是一个 “内联” 语句或表达式

匿名函数的优越性在于可以直接使用函数内的变量,不必申明

Go 语言使用 func() 定义匿名函数

语法

Go 语言中定义闭包函数的语法格式如下

func([parameter_list]) [return_type] {
   // 函数体
}

与一般函数的区别就是,闭包函数没有 函数名

范例

下面的范例,我们创建了一个函数 getSequence() 返回另外一个函数,该函数的目的是在闭包中递增 i 变量

/**
 * file: main.go
 * author: 搜云库技术团队(tech.souyunku.com)
 * Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
 */

package main

import "fmt"

func getSequence() func() int {
   i:=0
   return func() int {
      i+=1
     return i  
   }
}

func main(){
   /* nextNumber 为一个函数,函数 i 为 0 */
   nextNumber := getSequence()  

   /* 调用 nextNumber 函数,i 变量自增 1 并返回 */
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())

   /* 创建新的函数 nextNumber1,并查看结果 */
   nextNumber1 := getSequence()  
   fmt.Println(nextNumber1())
   fmt.Println(nextNumber1())
}

编译运行以上 Go 范例,输出结果如下

$ go run main.go 
1
2
3
1
2

干货推荐

本站推荐:精选优质专栏

附录:GOlang 教程:系列文章

赞(70) 打赏



未经允许不得转载:搜云库技术团队 » 四十一、Go 语言 – 闭包函数

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码
IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

评论 抢沙发

大前端WP主题 更专业 更方便

联系我们联系我们

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

微信扫一扫打赏


Fatal error: Uncaught Exception: Cache directory not writable. Comet Cache needs this directory please: `/data/wangzhan/tech.souyunku.com.wp/wp-content/cache/comet-cache/cache/https/tech-souyunku-com/index.q`. Set permissions to `755` or higher; `777` might be needed in some cases. in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php:367 Stack trace: #0 [internal function]: WebSharks\CometCache\Classes\AdvancedCache->outputBufferCallbackHandler() #1 /data/wangzhan/tech.souyunku.com.wp/wp-includes/functions.php(5109): ob_end_flush() #2 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(303): wp_ob_end_flush_all() #3 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(327): WP_Hook->apply_filters() #4 /data/wangzhan/tech.souyunku.com.wp/wp-includes/plugin.php(470): WP_Hook->do_action() #5 /data/wangzhan/tech.souyunku.com.wp/wp-includes/load.php(1097): do_action() #6 [internal function]: shutdown_action_hook() #7 {main} thrown in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php on line 367