#How do I call functions from other files in the same directory?

17 messages · Page 1 of 1 (latest)

sterile glacier
#

File structure:

folder/
   main.go
   file2.go

How do I import a function, xyz, from file2.go into main.go? I've tried importing it like so:

//**main.go**
import "file2"
xyz()

Then I read that two go files in the same directory are considered as part of the same "package" so i just tried calling the function without importing the file, but that didnt work either.

full cradle
#

Do they both have the same package name

sterile glacier
#

yeah

#

both have package main at the top

full cradle
#

Show the code

stray prairie
#

how are you running the code

sterile glacier
#

main.go

package main

func main() {
    xyz()
}

file2.go

package main

import "fmt"

func xyz() {
    fmt.Println("Hello from file2, world!")
}
sterile glacier
#

from the terminal

stray prairie
#

you want “go run .” not go run main.go if you’re running multiple files

sterile glacier
#

ahhh

#

yeah, it works now

#

thanks :)

#

how do i close this post?

hidden sail
#

🙂

fringe hazel
#

use /sloved, oh it's already closed... my bad

sterile glacier
#

ah