ADVERTISEMENT
ADVERTISEMENT

Avoid annoying errors 'declared and not used', 'imported and not used' in Golang?

Golang | Avoid / Skip Annoying Errors: Learn how to remove annoying errors 'declared and not used', 'imported and not used' in Golang?
Submitted by IncludeHelp, on November 23, 2021

In the Go programming language, if any variable is declared and not used in the code – then the compiler displays the error "declared and not used". For good programming practice, we have to remove those unused variables or unused packages from the code. It will save the memory and compilation, execution time.

Still, if you don't want to remove those unused variables or packages – you can avoid them by using the blank identifier (_).

Consider the below examples.

Example 1: Error - "imported and not used"

package main

import (
	"fmt"
	"os"
)

func main() {
	name := "Alex"

	fmt.Println("Name is:", name)
}

In the above code, two packages fmt and os are imported but os was not used, Thus, the following error will return.

./main.go:5:2: imported and not used: "os"

To avoid this error – Use a blank identifier (_) before the package name os.

package main

import (
	"fmt"
	_ "os"
)

func main() {
	name := "Alex"

	fmt.Println("Name is:", name)
}

Output:

Name is: Alex

Example 2: Error - "declared and not used"

package main

import (
	"fmt"
)

func main() {
	name := "Alex"
	age := 21

	fmt.Println("Name is:", name)
}

In the above code, two variables name and age are declared but age was not used, Thus, the following error will return.

./prog.go:9:2: age declared but not used

To avoid this error – Assign the variable to a blank identifier (_).

package main

import (
	"fmt"
)

func main() {
	name := "Alex"
	age := 21

	fmt.Println("Name is:", name)
	_ = age
}

Output:

Name is: Alex

Golang FAQ »

ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.