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