Saturday, 6 April 2013

Scanf in Go lang on Windows

A little gotcha when using fmt.Scanf in Go:

fmt.Scanf currently relies on the Unix line ending \n, while Windows uses \r\n. This means that when using fmt.Scanf, you must include the \n if you're building your Go program for Windows. For example:
 fmt.Scanf("%d", &num)  
will work in Unix but not in Windows. You're most likely to notice this when using fmt.Scanf multiple times - either in a for loop or simply sequentially. fmt.Scanf will likely appear to run twice as often as you expect, leading to unexpected program flow.

To resolve this issue, just make sure to include the \n in your use of fmt.Scanf, as demonstrated below.
 fmt.Scanf("%d\n", &num)  

Incidentally, if you're trying to track down errors like this one, you can always check function error codes, as demonstrated below.
  n, err := fmt.Scanf("%d", &num)  
     if err != nil {  
       fmt.Println(n, err)  
     }  
In the above case, we get this error:
 20 unexpected newline  
Which gives us the line number, and the issue from that line.



[References] Stack Overflow: parallel processing: How do I use fmt.Scanf in Go