当前位置:网站首页>Go语言之return语句的几种用法
Go语言之return语句的几种用法
2022-07-21 05:22:00 【慕城南风】
分三种情况
(以下 “指定返回值”这句话, 仅指return后面直接跟着的返回值)
- 退出执行,不指定返回值
(1) 函数没有返回值
package main
import (
"fmt"
)
func GetMoney(){
fmt.Println("money")
return
}
func main(){
GetMoney()
}
//什么都不输出
运行结果:
上边的示例代码中,GetMoney()是一个没有返回值的函数,这个函数中的return就是一个不带返回值的退出。
(2) 函数返回值有变量名
package main
import (
"fmt"
)
func GetMoney() (_amount int){
_amount = 88
fmt.Println("money: ",_amount)
return
}
func main(){
var amount = GetMoney()
fmt.Println("money: ",amount)
}
运行结果:
money: 88
money: 88
上边的示例代码中,GetMoney()是带一个返回值的函数,由于在返回值中定义了变量_amount,所以,在函数退出时,可以不用显示的在return后边指定函数返回值,函数调用结束后,自动将之前定义的返回值变量作为这个函数的返回结果。
- 退出执行,指定返回值
package main
import (
"fmt"
)
func GetMoney() (_amount int){
fmt.Println("money: ",_amount)
return 88
}
func main(){
var amount = GetMoney()
fmt.Println("money: ",amount)
}
运行结果:
money: 0
money: 88
- 退出执行,指定返回值和指定默认值
package main
import (
"fmt"
)
func GetMoney() (_amount int){
_amount = 99 //如果return后面没有指定返回值,就用赋给“返回值变量”的值
fmt.Println("money: ",_amount)
return 88 //如果return后面跟有返回值,就使用return后面的返回值
}
func main(){
var amount = GetMoney()
fmt.Println("money: ",amount)
}
运行结果:
money: 99
money: 88
边栏推荐
猜你喜欢
solr部署以及ik中文分词案例
DHCP服务与配置
JasperReports配置中文字体
OSPF的路由控制和防环
bond网络模式
OSPF的优化和配置
Top and ifconfig commands
@Solution to the problem that the parameters in Hump format in the requestbody annotation transfer object cannot receive data
Federated learning: spatiotemporal data mining in federated scenarios
Summary of tcp/ip five layer and seven layer models (it is recommended to recite the full text)
随机推荐
环路接口实验
放苹果
VRRP虚拟路由冗余协议
Construction and use of SFTP and vsftp services
DNS domain name resolution
R5为ISP,只能进行IP地址配置,其所有地址均配为共有IP地址
Leakage current, no grounding protection measures... 1296 imported electric kettle have major potential safety hazards
OSPF实验
MQ usage scenarios
Host information collection script
3. Use playbook in ansible
2.Ansible中常用模塊
OSPF和RIP
DataX environment deployment and test cases
[1260. 2D grid migration]
I spent 6000 to sign up for the test training class. Three months later, I successfully "cheated" into Tencent with a monthly salary of 17k
JasperReports配置中文字体
N皇后
BGP相关知识点
Exness: the US index fell for three consecutive days, and the euro rebounded to digest the expectation of interest rate hike