Golang基础 Label标签与goto跳转

使用方法

  • Label 和goto是必须的

  • Label可以声明再函数体的任何地方

  • Label的作用范围是在函数体中

  • Label在嵌套函数(闭包)是不可用的. 不管是在闭包里调用闭包外的Label, 还是在闭包外调用闭包里的Label

  • 变量的声明必须在goto之前

示例

Go 复制代码
package main

import "fmt"

func main() {
	fmt.Println("1")
	goto End

	fmt.Println("2")
End:
	fmt.Println(3)
}

输出:

bash 复制代码
1
3

Label在嵌套函数(闭包)是不可用的

bash 复制代码
package main

import (
	"fmt"
)

func main() {
	fmt.Println(1)
	func() {
		fmt.Println("Nested function")
		goto End
	}()
End:
	fmt.Println(2)
}

输出:

bash 复制代码
# devops/test
.\study.go:11:8: label End not defined
.\study.go:13:1: label End defined and not used

参考文档

bash 复制代码
https://www.cnblogs.com/zhangyafei/p/13938116.html
相关推荐
踩着两条虫2 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB2 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
Spider Cat 蜘蛛猫2 小时前
Springboot SSO系统设计文档
java·spring boot·后端
即使再小的船也能远航2 小时前
【Python】安装
开发语言·python
Irissgwe2 小时前
类与对象(三)
开发语言·c++·类和对象·友元
雪度娃娃3 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++
zyk_computer4 小时前
AI 时代,或许 Rust 比 Python 更合适
人工智能·后端·python·ai·rust·ai编程·vibe coding
萌新小码农‍4 小时前
python装饰器
开发语言·前端·python
KK溜了溜了4 小时前
Python从入门到精通
服务器·开发语言·python
雨辰AI4 小时前
SpringBoot3 项目国产化改造完整流程|从 MySQL 到人大金仓落地
java·数据库·后端·mysql·政务