Run Golang project with multiple files on Goland - go

I'm new to the Go language and have a problem when I'm trying to run a simple project which contains two files, on Goland IDE.
The first file called main -
package main
import "fmt"
func main() {
card := list{0, add(0)}
cards := append(card, add(3))
cards = append(card, add(4))
for i, c := range cards {
fmt.Println(i, c)
}
}
func add(x int) int {
return x + 1
}
And the second file called list -
package main
type list []int
When I'm trying to use the second file from the first file (use list type) I get compilation failed and -
command-line-arguments
.\main.go:6:10: undefined: list
What have I missed?

Ok, I got it, the Package option should be chosen instead of the File option -

Related

How do you properly set up a Golang library?

I've tried many times to set up a REAL go package with the modules system and store code in pkg. All the tutorials I've found are too basic, creating a module with go files stores at the top level, and I keep getting no Go files in /usr/local/go/github.com/me/mypackage.
I've tried a bunch of different things, but I can't get it to work properly...
GOROOT is set to /usr/local/go. I created a package here /usr/local/go/github.com/me/mypackage.
go.mod
module github.com/me/mypackage
go 1.18
pkg/main.go
package mypackage
// Add is our function that sums two integers
func Add(x, y int) (res int) {
return x + y
}
// Subtract subtracts two integers
func Subtract(x, y int) (res int) {
return x - y
}
pkg/main_test.go
package mypackage
import "testing"
func TestAdd(t *testing.T){
got := Add(4, 6)
want := 10
if got != want {
t.Errorf("got %q, wanted %q", got, want)
}
}
And I run: go test
What am I doing wrong? I find Go so frustrating to set up because languages/runtimes like Rust and NodeJS have very friendly package managers and are real easy to setup.
I'm trying to structure a library as described in this guidance for structuring go packages.
Don't confuse modules with packages.
One module might hold many packages.
Like this:
module_dir/package1_dir
module_dir/package2_dir
Try this layout:
Repository: github.com/me/mymodule
mymodule/mypkg
mymodule/mypkg/mypkg_test.go
mymodule/mypkg/mypkg.go
mymodule/go.mod
In mypkg.go and mypkg_test.go declare package mypkg.
Otherwise, run this script and it will create a correct layout for you:
https://gist.github.com/udhos/695d3be51fb4c7d151b4e252cdec3c63

Get Name of Current Module in Go

I am attempting to create named loggers automatically for HTTP handlers that I'm writing, where I am passed a function (pointer).
I'm using the code mentioned in this question to get the name of a function:
package utils
import (
"reflect"
"runtime"
)
func GetFunctionName(fn interface{}) string {
value := reflect.ValueOf(fn)
ptr := value.Pointer()
ffp := runtime.FuncForPC(ptr)
return ffp.Name()
}
I'm using this in my main function to try it out like so:
package main
import (
"github.com/naftulikay/golang-webapp/experiments/functionname/long"
"github.com/naftulikay/golang-webapp/experiments/functionname/long/nested/path"
"github.com/naftulikay/golang-webapp/experiments/functionname/utils"
"log"
)
type Empty struct{}
func main() {
a := long.HandlerA
b := path.HandlerB
c := path.HandlerC
log.Printf("long.HandlerA: %s", utils.GetFunctionName(a))
log.Printf("long.nested.path.HandlerB: %s", utils.GetFunctionName(b))
log.Printf("long.nested.path.HandlerC: %s", utils.GetFunctionName(c))
}
I see output like this:
github.com/naftulikay/golang-webapp/experiments/functionname/long.HandlerA
This is okay but I'd like an output such as long.HandlerA, long.nested.path.HandlerB, etc.
If I could get the Go module name (github.com/naftulikay/golang-webapp/experiments/functionname), I can then use strings.Replace to remove the module name to arrive at long/nested/path.HandlerB, then strings.Replace to replace / with . to finally get to my desired value, which is long.nested.path.HandlerB.
The first question is: can I do better than runtime.FuncForPC(reflect.ValueOf(fn).Pointer()) for getting the qualified path to a function?
If the answer is no, is there a way to get the current Go module name using runtime or reflect so that I can transform the output of runtime.FuncForPC into what I need?
Once again, I'm getting values like:
github.com/naftulikay/golang-webapp/experiments/functionname/long.HandlerA
github.com/naftulikay/golang-webapp/experiments/functionname/long/nested/path.HandlerB
github.com/naftulikay/golang-webapp/experiments/functionname/long/nested/path.HandlerC
And I'd like to get values like:
long.HandlerA
long.nested.path.HandlerB
long.nested.path.HandlerC
EDIT: It appears that Go does not have a runtime representation of modules, and that's okay, if I can do it at compile time that would be fine too. I've seen the codegen documentation and I'm having a hard time figuring out how to write my own custom codegen that can be used from go generate.
The module info is included in the executable binary, and can be acquired using the debug.ReadBuildInfo() function (the only requirement is that the executable must be built using module support, but this is the default in the current version, and likely the only in future versions).
BuildInfo.Path is the current module's path.
Let's say you have the following go.mod file:
module example.com/foo
Example reading the build info:
bi, ok := debug.ReadBuildInfo()
if !ok {
log.Printf("Failed to read build info")
return
}
fmt.Println(bi.Main.Path)
// or
fmt.Println(bi.Path)
This will output (try it on the Go Playground):
example.com/foo
example.com/foo
See related: Golang - How to display modules version from inside of code
If your goal is to just have the name of the module available in your program, and if you are okay with setting this value at link time, then you may use the -ldflags build option.
You can get the name of the module with go list -m from within the module directory.
You can place everything in a Makefile or in a shell script:
MOD_NAME=$(go list -m)
go build -ldflags="-X 'main.MODNAME=$MOD_NAME'" -o main ./...
With main.go looking like:
package main
import "fmt"
var MODNAME string
func main() {
fmt.Println(MODNAME) // example.com
}
With the mentioned "golang.org/x/mod/modfile" package, an example might look like:
package main
import (
"fmt"
"golang.org/x/mod/modfile"
_ "embed"
)
//go:embed go.mod
var gomod []byte
func main() {
f, err := modfile.Parse("go.mod", gomod, nil)
if err != nil {
panic(err)
}
fmt.Println(f.Module.Mod.Path) // example.com
}
However embedding the entire go.mod file in your use case seems overkill. Of course you could also open the file at runtime, but that means you have to deploy go.mod along with your executable. Setting the module name with -ldflags is more straightforward IMO.

How to call function from other file

structure
.
├── deck.go
└── main.go
Here is the code in each .go file
main.go
package main
func main() {
cards := newDeck()
cards.print()
}
deck.go
package main
import "fmt"
type card struct {
value string
suit string
}
type deck []card
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, card{
suit: suit,
value: value,
})
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Printf("%d) %s of %s\n", i, card.value, card.suit)
}
}
Why I can't run main.go file? please help TT
❯ go version
go version go1.14.3 darwin/amd64
❯ go run main.go
# command-line-arguments
./main.go:4:11: undefined: newDeck
Modules in Golang are determined by their parent folder. Across modules, the object must be capitalized to be exported. This is not your case.
Your error is in the compilation stage; this is similar to gcc when it can't find header files. You have to tell the Go compiler to search all files in the current module.
go run .
This tells go to include all files in the current (.) module (folder). Since newDeck is in a different file and the compiler is only running main, it can't find newDeck. But if you run all files, it will search and find the func in deck.go.
go run main.go runs only that file. You need to do go build . and run the executable.

Undefined Variables Within a Package During Build

I have two files within one package named db, one of which has a few unexported variables defined. Another one is a test file and would need to use these variables like so:
(This is the structure of the project)
$GOPATH/src/gitlab.com/myname/projectdir
├── main.go
└── db
├── add.go
└── add_test.go
(Here is a terse variation of the files)
db/add.go
package db
func Add(x, y int) int {
return x + y
}
// some other functions that use a and b from `add_test.go`
db/add_test.go
package db
import (
"testing"
)
var (
a = 1
b = 2
)
// test function use variables from add.go
func testAdd(t *testing.T) {
result := add(a, b)
if result != 3 {
t.Error(err)
}
}
Running go test within db/ directory passed, but once I ran go run main go it produced the following error:
db/add.go:: undefined: a
db/add.go:: undefined: b
Seems like add.go cannot find a and b from add_test.go during the build.
main.go
package main
import (
"fmt"
"gitlab.com/myname/projectdir/db"
)
func main() {
res := db.Add(1, 2)
fmt.Println(res)
}
Is this because add_test.go is not included during the build?
This is just the way how go tool works.
_test.go files are compiled only when you run go test. When a package is imported from another package any code from its _test.go files is not used.
Try running go build or go install from inside db package. It will fail.
Relative paths are touchy in Go. For one, I think you need to prefix them with import "./db". Another thing is that you should be in your $GOPATH/src location.
Try this:
move your files under the $GOPATH/src/project and $GOPATH/src/project/db directories.
prefix your import path with ./db for the DB package.
As for the IDE, that's all up to whatever plugins you are using. Try running the tools yourself: golint, go vet, oracle, etc to see the actual go warnings and errors.
Test functions should start with Test. that is what the documentation says.
func TestAdd(t *testing.T) {
result := Add(a, b)
if result != 3 {
t.Errorf("expected 3, got %d ", result)
}
}
Cheers.

How to call function from another file in Go

I want to call function from another file in Go. Can any one help?
test1.go
package main
func main() {
demo()
}
test2.go
package main
import "fmt"
func main() {
}
func demo() {
fmt.Println("HI")
}
How to call demo in test2 from test1?
You can't have more than one main in your package.
More generally, you can't have more than one function with a given name in a package.
Remove the main in test2.go and compile the application. The demo function will be visible from test1.go.
Go Lang by default builds/runs only the mentioned file. To Link all files you need to specify the name of all files while running.
Run either of below two commands:
$go run test1.go test2.go. //order of file doesn't matter
$go run *.go
You should do similar thing, if you want to build them.
I was looking for the same thing. To answer your question "How to call demo in test2 from test1?", here is the way I did it. Run this code with go run test1.go command. Change the current_folder to folder where test1.go is.
test1.go
package main
import (
L "./lib"
)
func main() {
L.Demo()
}
lib\test2.go
Put test2.go file in subfolder lib
package lib
import "fmt"
// This func must be Exported, Capitalized, and comment added.
func Demo() {
fmt.Println("HI")
}
A functional, objective, simple quick example:
main.go
package main
import "pathToProject/controllers"
func main() {
controllers.Test()
}
control.go
package controllers
func Test() {
// Do Something
}
Don't ever forget: Visible External Functions, Variables and Methods starts with Capital Letter.
i.e:
func test() {
// I am not Visible outside the file
}
func Test() {
// I am VISIBLE OUTSIDE the FILE
}
If you just run go run test1.go and that file has a reference to a function in another file within the same package, it will error because you didn't tell Go to run the whole package, you told it to only run that one file.
You can tell go to run as a whole package by grouping the files as a package in the run commaned in several ways. Here are some examples (if your terminal is in the directory of your package):
go run ./
OR
go run test1.go test2.go
OR
go run *.go
You can expect the same behavior using the build command, and after running the executable created will run as a grouped package, where the files know about eachothers functions, etc. Example:
go build ./
OR
go build test1.go test2.go
OR
go build *.go
And then afterward simply calling the executable from the command line will give you a similar output to using the run command when you ran all the files together as a whole package. Ex:
./test1
Or whatever your executable filename happens to be called when it was created.
Folder Structure
duplicate
|
|--duplicate_main.go
|
|--countLines.go
|
|--abc.txt
duplicate_main.go
package main
import (
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts)
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
countLines.go
package main
import (
"bufio"
"os"
)
func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
}
go run ch1_dup2.go countLines.go abc.txt
go run *.go abc.txt
go build ./
go build ch1_dup2.go countLines.go
go build *.go
You can import functions from another file by declaring the other file as a module. Keep both the files in the same project folder.
The first file test1.go should look like this:
package main
func main() {
demo()
}
From the second file remove the main function because only one main function can exist in a package. The second file, test2.go should look like below:
package main
import "fmt"
func demo() {
fmt.Println("HI")
}
Now from any terminal with the project directory set as the working directory run the command:
go mod init myproject.
This would create a file called go.mod in the project directory. The contents of this mod file might look like the below:
module myproject
go 1.16
Now from the terminal simply run the command go run .! The demo function would be executed from the first file as desired !!
as a stupid person who didn't find out what is going on with go module
should say :
create your main.go
in the same directory write this in your terminal
go mod init "your module name"
create a new directory and go inside it
create a new .go file and write the directory's name as package name
write any function you want ; just notice your function must starts with capital letter
back to main.go and
import "your module name / the name of your new directory"
finally what you need is writing the name of package and your function name after it
"the name of your new dirctory" + . + YourFunction()
and write this in terminal
go run .
you can write go run main.go instead.
sometimes you don't want to create a directory and want to create new .go file in the same directory, in this situation you need to be aware of, it doesn't matter to start your function with capital letter or not and you should run all .go files
go run *.go
because
go run main.go
doesn't work.
Let me try.
Firstly
at the root directory, you can run go mod init mymodule (note: mymodule is just an example name, changes it to what you use)
and maybe you need to run go mod tidy after that.
Folder structure will be like this
.
├── go.mod
├── calculator
│ └── calculator.go
└── main.go
for ./calculator/calculator.go
package calculator
func Sum(a, b int) int {
return a + b
}
Secondly
you can import calculator package and used function Sum (note that function will have Capitalize naming) in main.go like this
for ./main.go
package main
import (
"fmt"
"mymodule/calculator"
)
func main() {
result := calculator.Sum(1, 2)
fmt.Println(result)
}
After that
you can run this command at root directory.
go run main.go
Result will return 3 at console.
Bonus: for ./go.mod
module mymodule
go 1.19
ps. This is my first answer ever. I hope this help.

Resources