Call function from another file - go

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

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 -

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.

Go test <function> returns undefined: <function>

Trying to run "go test sum_test.go" returns an error:
./sum_test.go:18:13: undefined: SumInt8
FAIL command-line-arguments [build failed]
I'm taking an introductory course in golang. Our teacher distributed a code-file, sum.go, and a testing-file, sum_test.go. Trying to run "go test" on sum_test.go returns the error above. The code runs fine on our teachers mac, and he's having difficulties recreating the problem. Here's my go environment settings: https://pastebin.com/HcuNVcAF
sum.go
package sum
func SumInt8(a, b int8) int8 {
return a + b
}
func SumFloat64(a, b float64) float64 {
return a + b
}
sum_test.go
package sum
import "testing"
// Check https://golang.org/ref/spec#Numeric_types and stress the limits!
var sum_tests_int8 = []struct{
n1 int8
n2 int8
expected int8
}{
{1, 2, 3},
{4, 5, 9},
{120, 1, 121},
}
func TestSumInt8(t *testing.T) {
for _, v := range sum_tests_int8 {
if val := SumInt8(v.n1, v.n2); val != v.expected {
t.Errorf("Sum(%d, %d) returned %d, expected %d",
v.n1, v.n2, val, v.expected)
}
}
}
I see no particular errors, so I expected "go test sum_test.go" to run, and succeed. However it seems it can't find the method SumInt8 in sum.go.
$ go help packages
Many commands apply to a set of packages:
go action [packages]
Usually, [packages] is a list of import paths.
An import path that is a rooted path or that begins with a . or ..
element is interpreted as a file system path and denotes the package
in that directory.
Otherwise, the import path P denotes the package found in the
directory DIR/src/P for some DIR listed in the GOPATH environment
variable (For more details see: 'go help gopath').
If no import paths are given, the action applies to the package in the
current directory.
As a special case, if the package list is a list of .go files from a
single directory, the command is applied to a single synthesized
package made up of exactly those files, ignoring any build constraints
in those files and ignoring any other files in the directory.
List all the files in the current directory used in the test:
go test sum_test.go sum.go
or simply test the complete package in the current directory.
go test
For example,
$ go test -v sum_test.go sum.go
=== RUN TestSumInt8
--- PASS: TestSumInt8 (0.00s)
PASS
ok command-line-arguments 0.002s
$
or, for the complete package
$ go test -v
=== RUN TestSumInt8
--- PASS: TestSumInt8 (0.00s)
PASS
ok so/sum 0.002s
$
Option '-v' produces verbose output.
sum_test.go:
package sum
import "testing"
// Check https://golang.org/ref/spec#Numeric_types and stress the limits!
var sum_tests_int8 = []struct {
n1 int8
n2 int8
expected int8
}{
{1, 2, 3},
{4, 5, 9},
{120, 1, 121},
}
func TestSumInt8(t *testing.T) {
for _, v := range sum_tests_int8 {
if val := SumInt8(v.n1, v.n2); val != v.expected {
t.Errorf("Sum(%d, %d) returned %d, expected %d",
v.n1, v.n2, val, v.expected)
}
}
}
sum.go:
package sum
func SumInt8(a, b int8) int8 {
return a + b
}
func SumFloat64(a, b float64) float64 {
return a + b
}

main.go:9: use of package str without selector

I have the following in the intepreter of Tour of Go:
package main
import (
"golang.org/x/tour/wc"
str "strings"
)
func WordCount(s string) map[string]int {
results := make(map[str]int)
words := str.Fields(s)
return map[string]int{"x": 1}
}
//func main() {
// wc.Test(WordCount)
//}
This is based on https://tour.golang.org/moretypes/23
My error is
tmp/sandbox169629521/main.go:9: use of package str without selector
Trying
results := make(map[str.string]int)
now fails with
tmp/sandbox424441423/main.go:9: cannot refer to unexported name strings.string
tmp/sandbox424441423/main.go:9: undefined: strings.string
"string" is a builtin. You don't need to do strings.string:
Docs: https://golang.org/pkg/builtin/#string

How can I parse []int JSON data in Go?

I try parse JSON data include integer array. But, I can't get integer array.
package main
import (
"encoding/json"
"fmt"
)
type Anything struct {
A []int `json:"a"`
}
func main() {
s := "{a:[1,2,3]}"
var a Anything
json.Unmarshal([]byte(s), &a)
fmt.Println(a.A)
}
I got empty array.
[]
How can I get [1, 2, 3]?
{a:[1,2,3]} is not valid JSON. Object keys must be double-quoted. Changing it like this works as expected:
s := "{\"a\":[1,2,3]}"
https://play.golang.org/p/qExZAeiRJy
You have an invalid JSON. You should replace it, for example like this: s := [{"a":[1,2,3]}] or maybe like this s := "[{\"a\":[1,2,3]}]".
You can edit your code to something like this:
package main
import (
"encoding/json"
"fmt"
)
type Anything struct {
A []int `json:"a"`
}
func main() {
// note here: `[{"a":[1,2,3]}]`
// or: s := "[{\"a\":[1,2,3]}]"
s := `[{"a":[1,2,3]}]`
var a []Anything
json.Unmarshal([]byte(s), &a)
fmt.Println(a)
}
Output:
[{[1 2 3]}]
You can run it on https://play.golang.org/p/H4GupGFpfP

Resources