tnblog
首页
视频
资源
登录

Go 条件与循环

6816人阅读 2020/8/30 16:49 总访问:3656690 评论:3 收藏:0 手机
分类: Go

go数据类型

Go 条件与循环

循环

与其他主要编程语言的差异


Go 语言仅支持循环关键字 for。可以从以下代码看出,循环时并没有小括号

  1. for j := 7;j <= 9; j++

代码示例


while 条件循环

  1. n := 0
  2. /* while(n<5) */
  3. for n < 5 {
  4. t.Log(n)
  5. n++
  6. }

无限循环

  1. /*while(true)*/
  2. n := 0
  3. for {
  4. ...
  5. }

if 条件

与其他语言差别不大(这里condition结果为bool值)

  1. if condition-1 {
  2. } else if condition-2{
  3. } else{
  4. }

举例

  1. func TestIfMultiSec(t *testing.T) {
  2. if a := 1 == 1; a {
  3. t.Log("1==1")
  4. }
  5. }

与其他主要编程语言的差异

  1. 支持变量赋值:
    1. if var declaration; condition{
    2. ......
    3. }

    举例

  1. func TestIfMultiSec(t *testing.T) {
  2. if v,err := someFun(); err==nil{
  3. t.Log("1==1")
  4. }else{
  5. t.Log("1==1")
  6. }
  7. }

switch 条件

  1. func TestSwitchMultiCase(t *testing.T) {
  2. for i := 0; i < 5; i++ {
  3. switch i {
  4. case 0, 2:
  5. t.Log("Event")
  6. case 1, 3:
  7. t.Log("Odd")
  8. default:
  9. t.Log("it is not 0-3")
  10. }
  11. }
  12. }

也可以这样写

  1. func TestSwitchCaseCondition(t *testing.T) {
  2. for i := 0; i < 5; i++ {
  3. switch {
  4. case i%2 == 0:
  5. t.Log("Event")
  6. case i%2 == 1:
  7. t.Log("Odd")
  8. default:
  9. t.Log("unknow")
  10. }
  11. }
  12. }

结果

在 case 中写 fallthrough 函数可以执行到下一个case大家可以自行测试


欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价
这一世以无限游戏为使命!
排名
2
文章
657
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 : 好是好,这个对效率影响大不大哇,效率高不高
ASP.NET Core 服务注册生命周期
剑轩 : http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术