dongqiuge5435 2019-03-13 11:59
浏览 29
已采纳

仅在init语句中一次输入函数

I am starting programming with Go and I am trying to create a program that makes queries to a DB and return the data. I have achieved this but I have encounter some problems and questions during this.

Firstly, I tried to create a for with a condition to tell the program when I want to stop making queries, but the Init Statement of the for looks that only is evaluated once -and I am never asked again to enter input via terminal- (I have read here that is because his value is hold and then it doesnt execute the function again: Golang switch statement only calls function once ):

Edited

func main() {
    var query string
    for query = ReadQuery(); query != "exit
"; {
        rows, err := db.Query(query)
        //Printing results and other operations
    }
    fmt.Println("Exiting")
}

func ReadQuery() string {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter query in a single line, with no newline. 'exit' to terminate execution: 
")
    query, _ :=reader.ReadString('
')
    reader.Reset(os.Stdin)
    return query
}

...so I have done this fix that looks to me a bit dirty:

func main() {
    var query string
    for {
        query = ReadQuery()
        if query == "exit
" {
            fmt.Println("Exiting")
            break
        }
        //Printing results and other operations
    }
}

func ReadQuery() string {
   reader := bufio.NewReader(os.Stdin)
   fmt.Print("Enter query in a single line, with no newline. 'exit' to terminate execution: 
")
   query, _ :=reader.ReadString('
')
   reader.Reset(os.Stdin)
   return query
}

So the question is if there is another way to do this using for statements and avoid more lines to my code. Lot of thanks

  • 写回答

1条回答 默认 最新

  • douxin2002 2019-03-13 12:34
    关注

    You need to add a post statement to your loop that will be called on each iteration.

    var query string
    for query = ReadQuery(); query != "exit
    "; query = ReadQuery() {
        // loop body
    }
    

    The Go Tour has a good explanation of this functionality.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度