dqwolwst50489 2017-07-06 15:55
浏览 71

在主线程和打印线程中定义goto

I have two questions about Go code. This is my program. This program controls the presence of a nickname in a "database".

package main

import "fmt"

func rcv(){
  if r := recover() ; r != nil {
    fmt.Println("retry.")
    main()  
  }
}
func main(){
defer rcv()
INSERT:
  fmt.Println("Insert a nickname: ")
  var s string
  fmt.Scanln(&s)
  switch { 
  case len(s) <= 0 : 
    fmt.Println(fmt.Errorf("error empty"))
    goto INSERT
  case s=="mark"||s=="andrea": 
    fmt.Println("Accept, the nickname is",s)
  default :
    fmt.Println("ATTENTION, nickname not found")
    panic("Error.")
  }
}

My questions are:

  1. Using the recover function ( rcv () ), at the end of it, the recalled of main() is sent running like another thread? The principal main() function ends when the second is executed or whenever the panic is raised, the recover function create another process? (example: if the input nickname is wrong 5 times, 5 more main functions are started, so 6 Main running functions?) If create multiple executions of the main(), is there a way to print threads/process id or something like that?

  2. I used the INSERT label and the goto construct. Can I use goto outside the main function (example: at the end of the rcv() function to return to the top of the main function)? I could use goto instead of calling the main() function at the end of the rcv()

  • 写回答

1条回答 默认 最新

  • drwurqczo39355510 2017-07-06 16:10
    关注

    1. About defer

    defer statement execute function BEFORE exiting scope. So stack of caller-func is remaining while executing defer-func.

    func foo() (err error) {
        defer func() {
            err = io.EOF
        }()
    }
    

    It will crash with stackoverflow

    2. About goto

    See documentation

    A "goto" statement transfers control to the statement with the corresponding label within the same function.

    So you can't label outside func.

    3. About question

    How do I get back to the beginning of the main () function?

    package main
    
    func Main() {
        // do your main
    }
    
    func main() {
        for {
            Main()
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 链接问题 C++LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接