Essential Go Strings  Suggest an edit

Read file line by line

Often we need to read a file line by line.

Read file into memory and split into lines

// ReadFileAsLines reads a file and splits it into lines
func ReadFileAsLines(path string) ([]string, error) {
	d, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	s := string(d)
	lines := strings.Split(s, "\n")
	return lines, nil
There are 32 lines in 'main.go'

Iterate over lines in a file

It’s more efficient to only process one line at a time, as opposed to reading the whole file into memory.

We can do that using bufio.Scanner:

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()
37 lines in 'main.go'

  ↑ ↓ to navigate     ↵ to select     Esc to close