TrimSuffix函数调试过程中的学习
在进行“猜数游戏”进行项目复现时,使用bufio获取输入
并先将输入去掉换行符后,由字符串类转为整形,从而获取输入的数
其中,去掉换行符有用到函数TrimSuffix
gohugo对于该函数的解释为
Given the string
"aabbaa"
, the specified suffix is only removed if"aabbaa"
ends with it:
意思为,若字符串以传入参数为结尾,则删除该结尾
故此在猜数代码中,删掉换行符的代码可以写为
input = strings.TrimSuffix(input, "\n")
然而却出现了报错
可以看到在字符串"10"中出现了"10\r",可以看到的确"\n"被删除了,然而却还剩一个"\r"
这其实是一个编码差异问题,在StackOverflow中,有一篇文章问道# What's the difference between \n and \r\n?
其下回答是:
\r
is a carriage return and\n
is a line feed, in old computers where it not have monitor, have only printer to get out programs result to user, if you want get printing from staring of new line from left, you must get\n
for Line Feed, and\r
for get Carriage return to the most left position, this is from old computers syntax saved to this time on Windows platform.
\n means new line. It means that the cursor must go to the next line.
\r
means carriage return. It means that the cursor should go back to the beginning of the line.
Unix programs usually only needs a new line (\n
).
Windows programs usually need both.
所以对于win用户来说,此处的代码应修改为
input = strings.TrimSuffix(input, "\r\n")