Hello, I’ve been messing around with go for the past few days. I’m making a simple ‘shell’ and when I’m using a switch case I need to put a space after my input for it to work correctly. For example lets say I have a case for “quit”, when typing in my ‘command’ I have to put "quit " and not “quit”. I don’t have this problem running my code in Goland or on repl.it, but running from the terminal in vscode, or windows terminal I get this unexpected behavior. Here is my sample code:
reader := bufio.NewReader(os.Stdin)
for {
text, _ := reader.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
fullText := strings.Split(text, " ")
switch fullText[0] {
case "quit":
os.Exit(-1)
}
}
Works as expected on Ubuntu when executed with go run main.go.
What happens when built and run in a windows shell ?
I would investigate the content of text after replace with and without trailing spaces. Simply print as a byte slice.
This might be a windows specific issue.
So some of your terminals use linux style line breaks, other use windows style line breaks. strings.TrimSpace should be able to help you. Apply it on the input string. Or strings.Trim with "\r" if you want to explicitely allow trailing whitespace
Sorry for responding a little late. Thank you guys so much for your help! strings.TrimSpace did the trick! Thanks for being patient with such a silly mistake and giving me such awesome detailed responses.