Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positive when scanning a file and incorrect line number for suggested preallocation #28

Open
kellen-miller opened this issue Apr 8, 2024 · 0 comments

Comments

@kellen-miller
Copy link

kellen-miller commented Apr 8, 2024

Example setup to reproduce the issue.

foo.txt

some dummy text

/* some comment */
more dummy text

// some comment
even more dummy text

main.go

type FooLine struct {
	Parts     []string
	LineFound int
}

type Foo struct {
	Words     []string
	LineFound int
}

func main() {
	file, err := os.Open("foo.txt")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	var (
		lines      = bufio.NewScanner(file)
		lineNumber int
		foos       []*Foo
	)
	for lines.Scan() {
		lineNumber++

		line := lines.Text()
		if line == "" || strings.HasPrefix(line, "//") || strings.HasPrefix(line, "/*") {
			continue
		}

		foos = append(foos, &Foo{
			Words:     strings.Split(line, " "),
			LineFound: lineNumber,
		})
	}

	if err := lines.Err(); err != nil {
		panic(err)
	}

	println(foos)
}

Running prealloc -forloops main.go outputs:
main.go:21 Consider preallocating foos

Two issues:

  1. Because I'm using a scanner, foos can't be preallocated. It's not possible to know information about the number of lines or data lines in the file.
  2. Minor issue: prealloc is identifying the problem on line 21, however, that is the opening declaration of the var block var (. foos is actually on line 24. Not sure if this is possible to remedy, and not a huge issue since prealloc names the slice to consider preallocating in the output.
@kellen-miller kellen-miller changed the title False positive when read a file line by line and incorrect line number for suggested preallocating False positive when scanning a file and incorrect line number for suggested preallocation Apr 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant