Unused function in package

1,004 views
Skip to first unread message

zsoumya

unread,
Aug 26, 2017, 3:43:06 PM8/26/17
to golang-nuts
Golang noob here trying to create a basic standalone package.

The package code is simple and is given below:

package Utils

import (
"bufio"
"os"
)

func ReadLine() string {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
return scanner.Text()
}

It works as expected but I get a editor warning (I am using Jetbrains Gogland) "Unused function 'ReadLine'". However if I change the function name to something like Read instead of ReadLine I don't get the warning. Can someone kindly explain why this happens?

Also, what needs to be done to get rid of this "unused function" warning while creating standalone packages. If I understand correctly, an exposed function in a package is supposed to be invoked by the package consumer and is unlikely to be used inside the package itself.

A reference to the Golang documentation where these topics are explained would be greatly appreciated.

Justin Israel

unread,
Aug 26, 2017, 4:36:59 PM8/26/17
to zsoumya, golang-nuts
You won't find a reference to this issue in the Go documentation, because unused functions isn't something the Go compiler warns about. There is a "go vet" command that performs some linting but unused functions isn't one of those:

What you are seeing is going to be coming from some linting action that your editor is performing. 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

zsoumya

unread,
Aug 26, 2017, 5:26:03 PM8/26/17
to golang-nuts, kokho...@gmail.com
Thanks. But why does ReadLine is reported as an unused function but not when the function is renamed to Read?

Florin Pățan

unread,
Aug 27, 2017, 3:38:45 AM8/27/17
to golang-nuts
There are chances that other function names will change the signature to match interfaces in your GOPATH, in which case Gogland will not mark the function as unused since it won't know if it's needed to implement that interface or not (given how interfaces work in Go).

Since Gogland looks in your whole GOPATH for usages of the package.Function and it can't find any, it then marks the function as unused.

If you want to have the function shown as use regardless of its name, there's a simple way to do so: write a test for it.

Florin Pățan

unread,
Aug 27, 2017, 3:39:14 AM8/27/17
to golang-nuts
Gogland does not use go vet.

zsoumya

unread,
Aug 27, 2017, 4:49:54 AM8/27/17
to golang-nuts
Thanks Florin. Your explanation makes a lot of sense. I'll also write tests going forward so that all exported functions are "used" at least once.
Reply all
Reply to author
Forward
0 new messages