<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 (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("/home/nicholas/Go/dictionary.txt")
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 < len(scanner.Text()){
newint = len(scanner.Text())
}
fmt.Println(newint)
}
}
</code></pre>
<hr/>**评论:**<br/><br/>Fwippy: <pre><p>You'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>