How to run a function from another package

hi, how to run a function from another package

I have 2 files

main.go
db.go

package main (both)

then I try execute func on db.go in main.go I get error- undefined: func…,

Can you paste your code?

1 Like

Package main is a bit special. Its not meant to be split across multiple files.

Either you need to specify each file when compiling, or you need to split into different packages.

1 Like

Hi

go run main.go other.go

And so on or

go run *.go

1 Like

no, I have this structure of project

[folder]
–main.go
–db.go

how I can properly import file db.go in main.go?

I know if I manually copy and paste file db.go in go path directory this will be worked…

but what if I just want to split the project into small files ?? How to correctly access the file in the same directory?

src/
| db/
| | db.go
| main.go

db/db.go

package db

func Fn() string {
	return "Hello!"
}

main.go

package main

import (
	"db"
	"fmt"
)

func main() {
	fmt.Println(db.Fn())
}
2 Likes

thanks for answer, I try it but fail(

Here’s a little breakdown of separating code into packages from GoStart. https://github.com/alco/gostart#3-how-do-i-split-my-package-into-multiple-files

A main package allows only one main function to be defined, so you’ll need to choose one single file from your main package to put it in.

See @luk4z7 for the solution, which is to create a db package and define your function in that package, import it into your main package.

1 Like

thanks all guys )) now it work!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.