Original post

Hello, I’ve been messing around with 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":

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.

Note that this is not really a switch problem.

Have you tried to debug your code using some output?

A fmt.Printf("%#v", fullText) can give you some insights.

Codewise there doesn’t seem to be any problem on a first glance and it should just work.

Hi Norbert,

[]string{“quitr”} -> quit
[]string{“quit”, “r”}-> quit

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


The windows systems print output “nr” so you must try “r” or “nr”

Yes, strings.TrimSpace is working.
Hi Nate , I have copied your code and tried. Thank you for the post.

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.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.