Jame Phankosol
Jame Phankosol

Reputation: 43

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

Upvotes: 3

Views: 2314

Answers (2)

Sumukha Pk
Sumukha Pk

Reputation: 124

go run main.go runs only that file. You need to do go build . and run the executable.

Upvotes: 0

justahuman
justahuman

Reputation: 637

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.

Upvotes: 5

Related Questions