Unable to use package across files - go

I am still learning Go, and I am stuck at this issue where I cannot use the struct I created in the main package
app.go
package main
import (
"fmt"
"log"
"database/sql"
// struct named App to hold our application
type App struct {
Router *mux.Router
DB *sql.DB
}
main_test.go
package main_test
import (
"testing"
"log"
"os"
)
// application we want to test
var a main.App // 👈 throws error
When I run the test go test -v, it throws the following error:
# pg_mux_test [pg_mux.test]
.\main_test.go:10:7: undefined: main 👈
FAIL pg_mux [build failed]

Disclaimer: I may not be giving a precise answer since it's not clear about your project structure, still making an attempt since I was at first very confused with imports in Go. And this is answer is valid only if you are using go packages (with go mod init stuff).
As an example, say your go.mod package name is main and your folder structure is something like:
.
├── app.go
├── go.mod
└── someDirName // (say main_test)
└── main_test.go
Then, you can import main package in your main_test.go as follows:
package main_test
import (
// ... other imports
"main" // 👈 import it here
)
// application we want to test
var a main.App // 👈 this time, it wont' throw error

Related

How to import a single go file in golang? Unable to import go file

Trying to import a file go file but unable to do so.
I have one main file:
main/
main.go
go_single_file.go
package main
import (
"./go_single_file"
)
func main() {
}
and go_single_file:
package go_single_file
func hello() bool{
return true
}
when i try to import go_single_file in my main file i get some sort of import error.
I am doing something wrong but not sure what.
If i make a separate package and import it then it works but not if it's in same folder.
Can anyone tell how can i import a go file from same folder.
In Golang files are organized into subdirectories called packages which enables code reusability.
The naming convention for Go package is to use the name of the directory where we are putting our Go source files. Within a single folder, the package name will be same for the all source files which belong to that directory.
I would recommend you to use go modules and your folders structure should be like this.
.
├── main.go
├── go.mod
├── go_single_file
│ └── go_single_file.go
In your go_single_file.go you are not using exported names for the function hello. So your file inside the go_single_file/go_single_file.go would look like this.
package go_single_file
func Hello() bool{
return true
}
Your main file would like this
package main
import (
"module_name/go_single_file"
)
func main() {
_ = go_single_file.Hello()
}

undefined main - testing code unable to acess main package

In the below code:
../folder1/some_test.go
package main_test
import "testing"
func TestF(t *testing.T) {
main.F()
}
../folder1/some_file.go
package main
func F() {
}
main.F() gives undefined main
$ go version
go version go1.14.3 linux/amd64
Renaming package name from main_test to main resolve the problem.
Why main_test package name is not allowed for testing code, in same folder?
You must import the package to use the package.
go.mod:
module example.app
main.go:
package main
func F() {}
func main() {}
main_test.go
package main_test
import (
"testing"
"example.app" // import the main package
)
func TestF(t *testing.T) {
main.F()
}
The code above assumes that main*.go are in the same directory as go.mod for package example.app. Replace example.app with the name of your module. Adjust the paths to match your application. For example, if the the main*.go files are in the directory cmd/example below the directory containing go.mod, use the import path example.app/cmd/example instead of example.app.
Note that a test can import a main package this way, but non-test code cannot.
The problem is that main_test is a different package from main.
To access functions in main you need to import main and access the functions like this: main.F()
Also, note f starts with lowercase and thus is not exported from the package main. To access it in main_test it needs to be exported (which can be done by changing it to start with a capital letter: F).
Alternatively, you can change the test file to be in package main.
Edit with a note: When importing main note that import paths are by directory name. Usually developers in Go put their packages in directories with the same name as the package (e.g. put main in a directory named main). In your case the package and directory names are different so the import will be import ".../folder1" not import ".../main". You'll still be able to use main.F() to access the function:
package main_test
import (
"testing"
"../folder1" // use the full path to folder1 from the root of your module
)
func TestF(t *testing.T) {
main.F()
}

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

How to write packages in go?

go is my first statically typed and compiled language so I am not sure about how to go about doing some things like writing packages...Should I write a package like...
package mypkg
import "fmt"
func mypkg {
fmt.Println("mypackage")
}
and then import this into the main package....install it and then test if it works?
Or should I write mypkg like this...
package main
import "fmt"
func mypkg() {
fmt.Println("mypackage")
}
func main() {
mypkg()
}
Should I do it this way to make sure that I can call go run mypkg and see if it works, then delete the main function and rename the package and then work on the rest of the library?
Or did I miss the point entirely and I should do something else?
Here are some basic steps to get you going if you want to use packages.
Create a folder called mypkg in the folder you're working in. In that folder create a mypkg.go file with the following code (note the capital letter in the function name. You need to do this so main.go can see it).
package mypkg
import "fmt"
func Mypkg {
fmt.Println("mypackage")
}
Now install the package just by typing go install while you're still in your mypkg directory. This will create a linkable object file you can use.
Now go back to your starting directory and create main.go with the following code:
package main
import (
"...(path to your mypkg folder)/mypkg"
"fmt"
)
func main() {
mypkg.Mypkg()
//optional
//fmt.Println("whatever")
}
Now run it by typing go run main.go. This will compile and run main.go that uses the previous mypkg package you created.

Go subpackage functions not imported properly

Trying to wrap my head around packages in Golang.
This is my workspace
/bin
/pkg
/src
/github.com
/esbenp
/testrepo
/subpackage
somefuncs.go
main.go
main.go
package main
import "github.com/esbenp/testrepo/subpackage"
func main() {
Somefunc()
}
somefuncs.go
package subpackage
import "fmt"
func Somefunc() {
fmt.Printf("yo")
}
I was under the impression that since Somefunc starts with an uppercase letter it would be exported for use in other files that imported it. The ouput I get in the console is.
main.go:4: imported and not used: "github.com/esbenp/testrepo/subpackage"
main.go:8: undefined: Somefunc
Can someone point me in the right direction?
You have to prefix the function by the name of the package is belongs to: subpackage.Somefunc().
In the case you have several subpackages with the same name, you have to alias them while importing them, or there will be a conflict:
import (
xapi "x/xx/xxx/api"
yapi "y/yy/yyy/api"
)
When you import a package it will be made available under its name.
To address Somefunc in your main.go you have to do
subpackage.Somefunc()

Resources