Home > Blockchain >  how to access sub directories in go's main file?
how to access sub directories in go's main file?

Time:10-26

I have a go project structured like this

--  go.mod

--  main.go

--  hello.go

--  folder1

    --  test.go

I want to access hloFunc from test.go file from the main file.

package folder1

import "fmt"

func hloFunc() {
    fmt.Println("Hello Function from sub directory")
}

I can't understand how importing a module/ package works. I have read articles and never understood anything. It'd be super helpful if I can get an insight as to what actually is happening here.

This is my go.mod file

module testModule

go 1.17

I can access any Function from hello.go file by simpling writing the name of the function in main file but I want to access functions from sub directories as well. How can I do that?

What I should I change in my main file to make this happen

package main

import "testModule/folder1/"

func main() {
    hloFunc()
}

CodePudding user response:

There are 2(at least) problems with your code. The first problem is the unnecessary trailing slash of the import path in main.go. You should remove it.

main.go

import "testModule/folder1"

The second problem is that you are trying to call an unexported function from another package. To fix that you should export it(by changing the first letter of the function name to uppercase) test.go

func HloFunc() {
    fmt.Println("Hello Function from sub directory")
}

and use the package name to call it.

main.go

func main() {
    folder1.Hlofunc()
}
  •  Tags:  
  • go
  • Related