Package imported but not used even if I clearly used the package

Issue

I don’t understand why importing local package in GO is such a pita. They often throw the "package imported but not used" error even if I clearly use the package in that same file! And then the code where I use it throws an "undeclared name" error as if I haven’t imported it but somehow you can’t identify.

Anyone can fix my problem? This isn’t the first this happened to me. A lot of times I just play around until it works, but now it becomes very annoying.

// go.mod

module final-project
// cmd/main.go

import (
    "final-project/infra"
    "final-project/handler"
)

func main() {
    db := config.DBInit()
    inDB := &handler.CommentHandler{DB: db}
}
// infra/config.go
package infra

import (
    "fmt"

    "final-project/entity"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)


func DBInit() *gorm.DB {
    dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        panic("Failed to connect to database")
    }

    fmt.Println("Database connected")

    db.AutoMigrate(structs.Comment{})
    return db
}

// handler/comments.go
package handler

import "net/http"

type CommentHandler struct{
    ///
}

func (u CommentHandler) Create(w http.ResponseWriter, r *http.Request) {
    ///
}
// entity/structs.go
package entity

import "time"

type Comment struct {
    ID uint
    Message   string
    CreatedAt time.Time
    UpdatedAt time.Time
}

This happends in all of lines of code where I try to import the any package from "final-project" module. And because of this, all codes where I used the package like db := config.DBInit() (imported from final-project/infra), db.AutoMigrate(structs.Comment{}) (imported from final-project/entity), etc throw the undeclared name errors (even if, as you can see, I’ve tried to import it). Why do my codes somehow not identify the imports? Anyone can help me?

Solution

You are importing it wrong it should not be file name

db := config.DBInit()

Instead it should be package name

db := infra.DBInit()

The same goes for structs.Comment{} which should be entity.Comment{}

Answered By – Chandan

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.