简体   繁体   English

找不到定制 package

[英]Can't find custom package

I'm tryng to create a custom package in go: i created folder project:我正在尝试在 go 中创建自定义 package:我创建了文件夹项目:

my_project
|_database
  |_database.go
main.go

but when i try to import it gaves me this error: "could not import database (no package for import database)"但是当我尝试导入时,它给了我这个错误:“无法导入数据库(导入数据库没有 package)”

i try to run "go init" as written in some tutorial and created a "go.mod" file, then i run "go install" and works fine, but in the main.go it still not working.我尝试按照一些教程中的说明运行“go init”并创建了一个“go.mod”文件,然后我运行“go install”并且工作正常,但在 main.go 中它仍然无法正常工作。 The project structure is now this:现在的项目结构是这样的:

my_project
|_database
  |_database.go
  |_go.mod
  |_go.sum
main.go

I work on windows with visual studio code我使用 Visual Studio 代码在 windows 上工作

Here is how i import the package:这是我导入 package 的方法:

import (
    "fmt"
    ...
    "database"
)

function main() {

You need to do a few things.你需要做几件事。

Make sure your database.go is the following way:确保您的 database.go 是以下方式:

it should contain a package name this case is database, comment the function/s that need to be used outside this package, use func instead of function.它应该包含一个 package 名称这种情况是数据库,注释需要在此 package 之外使用的函数,使用 func 而不是 ZC1C425268E68385D1AB5074C17A94F14。 and comment code and capitalize function name so it can be exported.并注释代码并大写 function 名称以便可以导出。

package database

import "fmt"

// Connect function to connect to my database
func Connect(){
   fmt.Print("connected...")
}

your main.go should be the following.您的 main.go 应该如下。

use func instead of function, import database based on folder position this case is./ use the package name database.使用 func 代替 function,基于文件夹 position 导入数据库。/使用 package 名称数据库。 because this function does not belong from current package main.因为这个 function 不属于当前 package 主。

package main

import "./database"

func main() {
   database.Connect()
}

This should be your folder structure.这应该是您的文件夹结构。

my_project
|_database
  |_database.go
main.go
go.mod 
go.sum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM