导入了包但没有使用,即使我明确使用了该包。

huangapple go评论80阅读模式
英文:

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

问题

我不明白为什么在GO中导入本地包会如此麻烦。即使我在同一个文件中明确使用了该包,它们经常会抛出“导入的包未使用”的错误!然后,我使用它的代码会抛出“未声明的名称”错误,好像我没有导入它,但你却无法识别。

有人可以解决我的问题吗?这不是我第一次遇到这种情况。很多时候我只是随便尝试,直到它能正常工作,但现在变得非常烦人。

这个问题发生在我尝试从“final-project”模块导入任何包的所有代码行中。正因为如此,我使用该包的所有代码,比如db := config.DBInit()(从final-project/infra导入),db.AutoMigrate(structs.Comment{})(从final-project/entity导入)等都会抛出“未声明的名称”错误(即使你可以看到,我已经尝试导入它)。为什么我的代码无法识别导入的包?有人可以帮帮我吗?

英文:

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?

答案1

得分: 3

你导入的方式有误,不应该使用文件名。应该使用包名来导入。

db := infra.DBInit()

同样,structs.Comment{}应该改为entity.Comment{}

英文:

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{}

huangapple
  • 本文由 发表于 2022年2月27日 14:06:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/71282520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定