go 流程控制

本文深入探讨了Go语言中的流程控制结构,包括条件判断(if/else)、开关语句(switch case)、循环(for)及标签与跳转(label与goto)。通过具体代码示例,详细解析了每种控制结构的用法和特点,为读者提供了全面的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、什么是流程控制?

 

二、If/else分支判断

2.1转译

package main

import (
	"fmt"
	"strconv"
)

func main ( ) {
	var str string
	fmt.Scanf("%s", &str)

	number, err := strconv.Atoi(str)
	if err != nil {
		fmt.Println("convert failed err:",err)
		return
	}

	fmt.Println(number)
}

  

三、switch case语句(开关)

package main

import "fmt"

func main() {
	var a int = 0

	switch a {
	case 0:
		fmt.Println("is 0")
		fallthrough //继续往下一个分支走
	case 10:
		fmt.Println("is 10")
	default:
		fmt.Println("is no")
	}
}
输出:

E:\project>main.exe
is 0
is 10

三、for 语句

写法1:for 初始化语句;条件判断;变量修改

 

3.1for-range结构

for 指针,值  := range 传入值{  }

package main

import "fmt"

func main(){
	str := "Go is a beautiful language!"
	fmt.Printf("The length of str is: %d\n", len(str))
	for pos, char := range str {
		fmt.Printf("Character on position %d is: %c \n",pos, char)
	}
}
//输出值

The length of str is: 27
Character on position 0 is: G
Character on position 1 is: o
Character on position 2 is:
Character on position 3 is: i
Character on position 4 is: s
Character on position 5 is:
Character on position 6 is: a
Character on position 7 is:
Character on position 8 is: b
Character on position 9 is: e
Character on position 10 is: a
Character on position 11 is: u
Character on position 12 is: t
Character on position 13 is: i
Character on position 14 is: f
Character on position 15 is: u
Character on position 16 is: l
Character on position 17 is:
Character on position 18 is: l
Character on position 19 is: a
Character on position 20 is: n
Character on position 21 is: g
Character on position 22 is: u
Character on position 23 is: a
Character on position 24 is: g
Character on position 25 is: e
Character on position 26 is: !

  

 四、laber与goto

做标记使用

 

转载于:https://www.cnblogs.com/liubiaos/p/9363462.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值