0
点赞
收藏
分享

微信扫一扫

golang跳转语句goto,break,continue的使用及区别说明

杰森wang 2022-03-14 阅读 79

goto

goto语句可以无条件地转移到过程中指定的行。

通常与条件语句配合使用。可用来实现条件转移, 构成循环,跳出循环体等功能。

在结构化程序设计中一般不主张使用goto语句, 以免造成程序流程的混乱

goto对应(标签)既可以定义在for循环前面,也可以定义在for循环后面,当跳转到标签地方时,继续执行标签下面的代码。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

func main() {

 // 放在for前面,此例会一直循环下去

 Loop:

 fmt.Println("test")

 for a:=0;a<5;a++{

  fmt.Println(a)

  if a>3{

   goto Loop

  }

 }

}

func main() {

 for a:=0;a<5;a++{

  fmt.Println(a)

  if a>3{

   goto Loop

  }

 }

 Loop:   //放在for后边

 fmt.Println("test")

}

break

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

func main() {

 Loop:

 for j:=0;j<3;j++{

  fmt.Println(j)

  for a:=0;a<5;a++{

   fmt.Println(a)

   if a>3{

    break Loop

   }

  }

 }

}

//在没有使用loop标签的时候break只是跳出了第一层for循环

//使用标签后跳出到指定的标签,break只能跳出到之前,如果将Loop标签放在后边则会报错

//break标签只能用于for循环,跳出后不再执行标签对应的for循环

continue

continue和标签的使用类似于break,这里不再详述

总结

goto语句本身就是做跳转用的,而break和continue是配合for使用的。所以goto的使用不限于for,通常与条件语句配合使用

在for循环中break和continue可以配合标签使用。

补充:golang 实现Location跳转

golang作为互联网时代的C语言,对网络的支持是非常友好的,最近想做个短网址转发使用,自然想到用Golang开发。

闲话少说,直接上源码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package main

  

import (

 "fmt"

 "log"

 "net/http"

)

func login(w http.ResponseWriter, r *http.Request) {

 fmt.Print(fmt.Sprintf("%v+", r))

 w.Header().Set("Cache-Control", "must-revalidate, no-store")

 w.Header().Set("Content-Type", " text/html;charset=UTF-8")

 w.Header().Set("Location", "http://wap.baidu.com/")//跳转地址设置

 w.WriteHeader(307)//关键在这里!

}

func main() {

 http.HandleFunc("/", login)    //设置访问的路由

 err := http.ListenAndServe(":9090", nil) //设置监听的端口

 if err != nil {

 log.Fatal("ListenAndServe: ", err)

 }

}

举报

相关推荐

0 条评论