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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看