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…,
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?
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.
Hi
go run main.go other.go
And so on or
go run *.go
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())
}
thanks for answer, I try it but fail(
Here’s a little breakdown of separating code into packages from GoStart. GitHub - alco/gostart: A getting started guide for Go newcomers
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.
thanks all guys )) now it work!
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.