Peculiar result

blov · · 458 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Why does the following code basically print out the length of each word in a line rather than the length of each word in a line SO LONG as it was greater than the last?</p> <p>Im sure im just screwing up simple logic. But i tried very similar code in python and i got the result i wanted.</p> <pre><code> package main import ( &#34;bufio&#34; &#34;fmt&#34; &#34;os&#34; ) func main() { file, err := os.Open(&#34;/home/nicholas/Go/dictionary.txt&#34;) if err != nil { fmt.Println(err) os.Exit(1) } defer file.Close() reader := bufio.NewReader(file) scanner := bufio.NewScanner(reader) for scanner.Scan() { newint :=0 if newint &lt; len(scanner.Text()){ newint = len(scanner.Text()) } fmt.Println(newint) } } </code></pre> <hr/>**评论:**<br/><br/>Fwippy: <pre><p>You&#39;re doing <code>newint := 0</code> - the use of the <code>:=</code> operator effectively redeclares a new newint each time.</p> <p>Move the declaration of <code>newint</code> outside of the loop, and use regular <code>=</code> to assign to it.</p></pre>Prerogativ: <pre><p>i knew it must have been something small and absurd haha</p> <p>thanks man</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

458 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传