How to call function from other file - go

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.

Related

Run Golang project with multiple files on Goland

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 -

API to get the module name

Is there an API to get the module name of a project which uses go 1.11 module system?
so I need to get abc.com/a/m from the module definition module abc.com/a/m in go.mod file.
As of this writing, I am not aware of any exposed APIs for that. However, looking at go mod sources, there is a function that can be quite useful in Go mod source file
// ModulePath returns the module path from the gomod file text.
// If it cannot find a module path, it returns an empty string.
// It is tolerant of unrelated problems in the go.mod file.
func ModulePath(mod []byte) string {
//...
}
func main() {
src := `
module github.com/you/hello
require rsc.io/quote v1.5.2
`
mod := ModulePath([]byte(src))
fmt.Println(mod)
}
Which outputs github.com/you/hello
Try this?
package main
import (
"fmt"
"io/ioutil"
"os"
modfile "golang.org/x/mod/modfile"
)
const (
RED = "\033[91m"
RESET = "\033[0m"
)
func main() {
modName := GetModuleName()
fmt.Fprintf(os.Stdout, "modName=%+v\n", modName)
}
func exitf(beforeExitFunc func(), code int, format string, args ...interface{}) {
beforeExitFunc()
fmt.Fprintf(os.Stderr, RED+format+RESET, args...)
os.Exit(code)
}
func GetModuleName() string {
goModBytes, err := ioutil.ReadFile("go.mod")
if err != nil {
exitf(func() {}, 1, "%+v\n", err)
}
modName := modfile.ModulePath(goModBytes)
fmt.Fprintf(os.Stdout, "modName=%+v\n", modName)
return modName
}
If your starting point is a go.mod file and you are asking how to parse it, I would suggest starting with go mod edit -json, which outputs a particular go.mod file in JSON format. Here is the documentation:
https://golang.org/cmd/go/#hdr-Edit_go_mod_from_tools_or_scripts
Alternatively, you could use rogpeppe/go-internal/modfile, which is a go package that can parse a go.mod file, and which is used by rogpeppe/gohack and some other tools from the broader community.
Issue #28101 I think tracks adding a new API to the Go standard library to parse go.mod files.
Here is a snippet of the documentation for go mod edit -json:
The -json flag prints the final go.mod file in JSON format instead of
writing it back to go.mod. The JSON output corresponds to these Go
types:
type Module struct {
Path string
Version string
}
type GoMod struct {
Module Module
Go string
Require []Require
Exclude []Module
Replace []Replace
}
type Require struct {
Path string
Version string
Indirect bool
}
Here is an example snippet of JSON output from go mod edit -json that shows the actual module path (aka module name), which was your original question:
{
"Module": {
"Path": "rsc.io/quote"
},
In this case, the module name is rsc.io/quote.
As of Go 1.12 (for those finding this via a search who are using modules but not necessarily the older version the OP mentioned), the runtime/debug package includes functionality for getting information about the build, including the module name. For example:
import (
"fmt"
"runtime/debug"
)
func main() {
info, _ := debug.ReadBuildInfo()
fmt.Printf("info: %+v", info.Main.Path)
}
You can run this example on the playground: https://go.dev/play/p/5oGbCRxSnjM
For more information, see the documentation for "runtime/debug".BuildInfo

Call function from another file

Inside my directory /go/src/lodo I have two files, main.go and uniqueElement.
uniqueElement.go
package main
import "fmt"
func unique(a []int) {
var value int
for i:= range a {
value = value ^ a[i]
}
fmt.Println(value)
}
main.go
package main
func main() {
var a = []int{1, 4, 2, 1, 3, 4, 2}
unique(a[0:])
}
I get an error
./main.go:7: undefined: unique
How can I correctly call unique from main?
You probably ran your code with go run main.go that only compiles and runs main.go try running go run main.go uniqueElement.go or building and running the binary generated
Change the name from unique to Unique.
The following codes work for me:
//module github.com/go-restful/article
package article
func IndexPage(w http.ResponseWriter, r *http.Request) {}
This func must be Exported, Capitalized, and Comment added
The use in main.go
//module github.com/go-restful
package main
import (article "github.com/go-restful/article")
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", article.IndexPage)
}

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