Go subpackage functions not imported properly - go

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

Related

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.

Relative imports in Go

I have a go Project with the following directory structure
utils(pkg)
| auth.go (has a function names test1)
controllers(pkg)
| login.go (has a function names test2)
I am trying to access function test1 from login.go. Here is what I have done
import "../utils"
func test2(c *gin.Context) bool{
utils.test1()
}
But I always get Unresolved reference test1. I am new to go . Can anyone help why I am getting this error?
No there is no relative import in Go.
you should use the absolute path considering GOPATH:
The GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you'll need to set when developing Go code. To get started, create a workspace directory and set GOPATH accordingly. see: https://golang.org/doc/code.html#GOPATH
Import paths
An import path is a string that uniquely identifies a package. A package's import path corresponds to its location inside a workspace
or in a remote repository (explained below).
The packages from the standard library are given short import paths
such as "fmt" and "net/http". For your own packages, you must choose a
base path that is unlikely to collide with future additions to the
standard library or other external libraries.
If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path. For
instance, if you have a GitHub account at github.com/user, that should
be your base path.
Note that you don't need to publish your code to a remote repository
before you can build it. It's just a good habit to organize your code
as if you will publish it someday. In practice you can choose any
arbitrary path name, as long as it is unique to the standard library
and greater Go ecosystem.
Example:
This example assumes you have set GOPATH=/goworkdir in your OS environment.
File: goworkdir/src/project1/utils/auth.go
package utils
func Test1() string {
return "Test1"
}
File: goworkdir/src/project1/controllers/login.go
package controllers
import "project1/utils"
func Test2() string {
return utils.Test1()
}
File: goworkdir/src/project1/main.go
package main
import (
"fmt"
"project1/controllers"
)
func main() {
fmt.Println(controllers.Test2())
}
Now if you go run main.go you should see output:
Test1
This is now different since the introduction of go modules, from go 1.11.
Thus, if you switch to go modules, and if your module is called "m", then the idiomatic way to do relative imports in your project tree would be to use: import "m/utils" and import "m/controllers" in places where you need to import those packages in your project.
For details, see:
https://github.com/golang/go/wiki/Modules#do-modules-work-with-relative-imports-like-import-subdir
GoLand users - by default these forms of imports appear as errors in the IDE. You need to enable Go Modules integration in settings
Here is another example project structure with file contents required to import correctly:
test1/
utils/
texts.go
main.go
go.mod
with following contents:
go.mod:
module mycompany.com/mytest
go 1.15
utils/texts.go (to make a function visible from a different package, it needs to start with an uppercase letter):
package utils
func GetText() string {
return "hello world"
}
main.go (only the full import name is supported, there is no shortcut to import from the same module easier):
package main
import (
"fmt"
"mycompany.com/mytest/test1/utils"
)
func main() {
fmt.Println(utils.GetText())
}
Given this directory configuration:
.
├── controllers
│   └── login.go
├── main.go
└── utils
└── auth.go
File main.go:
package main
import "./controllers"
func main() {
controllers.Test2("Hello")
}
File controllers/login.go:
package controllers
import "../utils"
func Test2(msg string) {
utils.Test1(msg)
}
File utils/auth.go:
package utils
import . "fmt"
func Test1(msg string) {
Println(msg)
}
Result works:
$ GO111MODULE=auto go build -o program main.go
$ ./program
Hello
So what you wanted to do works. The only difference is that I've used upper case function names, because it's required to export symbols.
I think you can just crate a vendor directory next to your source file, which acts like a relative GOPATH, and then create a relative symlink, which links to the package you want to import inside the vendor directory, and then import the package as if the vendor directory is your $GOPATH/src/.
It's possible as of Go 1.16, although still not as straightforward as it could be, by editing the go.mod file to resolve the package name to a relative path:
if you have a hello and a greeting packages side by side (hello contains main.go):
<home>/
|-- greetings/
|--go.mod <- init this as infra/greetings
|--greetings.go <- let's say that this package is called greetings
|-- hello/
|--go.mod <- init this as whatever/hello
|--main.go <- import infra/greetings
then edit hello's go.mod file and get the package:
go mod edit -replace infra/greetings=../greetings
go get infra/greetings
go mod tidy
There's a full example in the official documentation but hey, this might change again in the next version of Go.

undefined: function (declared in another package)

my project organisation looks like this :
GOPATH
src
cvs/user/project
main.go
utils
utils.go
main.go looks like this :
package main
import (
"fmt"
"cvs/user/project/utils"
)
func main() {
...
utilsDoSomething()
...
}
and utils.go :
package utils
import (
"fmt"
)
func utilsDoSomething() {
...
}
The compiler tells me that :
main.go imported and not used: "cvs/user/project/utils"
main.go undefined: utilsDoSomething
I don't know what I'm doing wrong. Any idea would be helpful, thank you in advance !
You forgot the package prefix in main.go and your function is not exported, meaning it is not accessible from other packages. To export an identifier, use a capital letter at the beginning of the name:
utils.UtilsDoSomething()
Once you have the utils prefix you can also drop the Utils in the name:
utils.DoSomething()
If you want to import everything from the utils package into the namespace of your main application do:
import . "cvs/user/project/utils"
After that you can use DoSomething directly.
When you are referencing a function from a package you need to reference it using the package name.Function name (with capital case).
In your case use it as:
utils.UtilsDoSomething().
In Go the symbols (including function names) starting with lower case letters are not exported and so are not visible to other packages.
Rename the function to UtilsDoSomething.
If you strongly oppose exporting this function and you are using Go 1.5 or later, you can make your function visible to only your project by placing utils directory inside internal directory.
Specification of internal packages

Resources