Why is my go lang string comparison not working as expected? -


i dipping toe go , have written code check if y or n input:

reader := bufio.newreader(os.stdin) fmt.print("(y / n): ") text, _ := reader.readstring('\n') text = strings.tolower(text)  if strings.compare(text, "y") == 0 {      fmt.println("true") } else {     fmt.println("else") } 

when run code & type y (and press enter) expect see true else - can see why?

you want like:

reader := bufio.newreader(os.stdin) fmt.print("(y / n): ") text, _ := reader.readstring('\n') text = strings.tolower(text[0:len(text)-1])  if strings.compare(text, "y") == 0 {     fmt.println("true") } else {    fmt.println("else") } 

as comment above says, readstring() returns delimiter part of string. you're getting "y\n" , comparing "y" - result false. (you might rather use trim() function remove whitespace either side of input,instead!)

edit: trim() suggestion should preferred on original suggestion. otherwise produces non-portable code, illustrated in comments answer. complete revised code:

reader := bufio.newreader(os.stdin) fmt.print("(y / n): ") text, _ := reader.readstring('\n')   text = strings.tolower(strings.trim(text," \r\n"))  if strings.compare(text, "y") == 0 {     fmt.println("true") } else {    fmt.println("else") } 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -