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 »




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.