简体   繁体   中英

Can't find custom package

I'm tryng to create a custom package in go: i created folder project:

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)"

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. 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

Here is how i import the package:

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

function main() {

You need to do a few things.

Make sure your database.go is the following way:

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. and comment code and capitalize function name so it can be exported.

package database

import "fmt"

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

your main.go should be the following.

use func instead of function, import database based on folder position this case is./ use the package name database. because this function does not belong from current package main.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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