Strings / Read file line by line / Essential Go

Run Settings
LanguageGo
Language Version
Run Command
package main import ( "fmt" "os" "bufio" ) func IterLinesInFile(filePath string, process func (s string) bool) error { file, err := os.Open(filePath) if err != nil { return err } defer file.Close() scanner := bufio.NewScanner(file) // Scan() reads next line and returns false when reached end or error for scanner.Scan() { line := scanner.Text() if !process(line) { return nil } // process the line } // check if Scan() finished because of error or because it reached end of file return scanner.Err() } func main() { nLines := 0 IterLinesInFile("main.go", func(s string) bool { nLines++ return true }) fmt.Printf("%d lines in 'main.go'\n", nLines) }
Editor Settings
Theme
Key bindings
Full width
Lines