Local Variable declaration

Hi! I just started on golang. I was doing a project in which I have to build a comic book management project. I initialized the variables inside the main function and then used the fmt to print but it did not give me anything. Below is the code:

package main

import "fmt"

func main() {
    var publisher string

var writer string

var artist string

var title string

var year int

var pageNumber int

var grade float32

    title = "Mr. GoToSleep"

    writer = "Tracey Hatchet"

    artist = "Jewel Tampson"

    publisher = "DizzyBooks Publishing Inc."

    year = 1997

    pageNumber = 14

    grade = 6.5

    fmt.Println(title, "written by", writer, "drawn by", artist, "Published by", publisher)


Hey there, welcome to the forums.

You should be seeing an error similar to this:

./main.go:7:7: year declared and not used
./main.go:7:13: pageNumber declared and not used
./main.go:8:7: grade declared and not used

Go programs with unused local variables do not compile. So how can we solve this?

Yes. I am only getting this and nothing else. The fmt.println is not giving out any result. I did try declaring global variables which worked but I still do not understand why local variables did not work.

This is a deliberate feature of the Go language.

The presence of an unused variable may indicate a bug […] Go refuses to compile programs with unused variables or imports, trading short-term convenience for long-term build speed and program clarity. Go FAQ: Can I stop these complaints about my unused variable/import?

Unused global variables are however allowed.

If you’ve declared the variables, you should be using them :wink:

Simply complete the fmt.Println, this is what the exercise is expecting anyway.

Thank you so much for clarifying the doubt. I wanted to know that if we declare a local variable, store some value in it and I don’t print it, the program won’t compile. Wouldn’t this be problematic in the long run when I will have local variables in multiple functions with values being stored in them but I am not printing those in the scope of the variables?

If you are not using variable(by printing or by any other means) inside the scope it would be of no use and as a local variable of a function it has no scope outside function so to keep your code clean and less confusing this deliberate functionality is added in Go.