Skip to content

bufio: scanner does not work if you pass a structure item as an argument #52420

@michail-vestnik

Description

@michail-vestnik

What version of Go are you using (go version)?

$ go version: go1.17 linux/amd64

Does this issue reproduce with the latest release?

Yes

Example code

I wrote a code example that demonstrates the problem well.

package main

import (
	"bufio"
	"fmt"
	"os"
)

type Example struct {
	file *os.File
}

func NewExample() *Example {

	f, _ := os.OpenFile("./fakedata.txt", os.O_APPEND|os.O_RDWR|os.O_CREATE, 0644)
        // fakedata.txt is a text file that contains three lines:
        // string 01
        // string 02
        // string 03

	ex := Example{
		file: f,
	}

	fmt.Printf("example.file 01: %v\n", &ex.file)

	scanner := bufio.NewScanner(ex.file)
	fmt.Println(scanner.Err())

	for scanner.Scan() {
		fmt.Printf("scanner.Text 01(): %v\n", scanner.Text())
	}

	return &ex

}

func (ex *Example) Scan() {

	fmt.Printf("example.file 02: %v\n", &ex.file) // same address!

	scanner := bufio.NewScanner(ex.file)
	fmt.Println(scanner.Err())

	for scanner.Scan() {
		fmt.Printf("scanner.Text 02(): %v\n", scanner.Text())
	}

}

func main() {

	example := NewExample()
	/*
		scanner.Text_01(): string 01
		scanner.Text_01(): string 02
		scanner.Text_01(): string 03
	*/

	example.Scan()
	// nothing

}

Why doesn't the scanner work if you pass it a file as a structure element, given the same address in memory?

Thanks/

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions