golang unreachable code 錯誤提示


golang:unreachable code 

有時候編譯器會出現 這樣的提示:unreachable code 

 

 

 

 

原因:是因為 出現提示位置的前面,有代碼 死循環、panic、或者 return  等,導致代碼永遠無法執行到目標位置。

 

 

案例:

案例1:死循環:

 

package main

import (
	"fmt"
	"time"
)

func main()  {


	for {
		fmt.Println("hello,world")
		time.Sleep(time.Second*2)
	}

	fmt.Println("hi") // 編譯器提示:unreachable code


	/*
	解決辦法就是把你把要調用的方法寫到return前面就好了
	*/

}

  

 

案例2:panic

 

package main

import "fmt"

func main()  {
	fmt.Println("hello,world")
	panic("Oh,good by") // 編輯器 提示:unreachable code
	fmt.Println("hello,world")


}

  

 

 

案例3:return

 

package main

import "fmt"

func main()  {
	fmt.Println("hello,world")
	return
	fmt.Println("hello,world") // 編輯器 提示:unreachable code


}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM