如何在Go的主文件中访问子目录?

huangapple go评论77阅读模式
英文:

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

问题

我有一个像这样结构的Go项目:

-- go.mod

-- main.go

-- hello.go

-- folder1

    -- test.go

我想从主文件中的test.go文件访问hloFunc函数。

package folder1

import "fmt"

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

我不理解如何导入模块/包。我已经阅读了一些文章,但从未理解过任何内容。如果我能够了解到这里实际发生了什么,那将非常有帮助。

这是我的go.mod文件:

module testModule

go 1.17

我可以通过在主文件中简单地写入函数名称来访问hello.go文件中的任何函数,但我也想从子目录中访问函数。我该如何做到这一点?

我应该在我的主文件中做出什么改变来实现这一点?

package main

import "testModule/folder1/"

func main() {
    hloFunc()
}
英文:

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

答案1

得分: 1

你的代码有两个问题。第一个问题是在main.go中导入路径的末尾有一个不必要的斜杠。你应该将其删除。

main.go

import "testModule/folder1"

第二个问题是你试图从另一个包中调用一个未导出的函数。要解决这个问题,你应该将其导出(通过将函数名的第一个字母改为大写)。
test.go

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

并使用包名来调用它。

main.go

func main() {
    folder1.Hlofunc()
}
英文:

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

huangapple
  • 本文由 发表于 2022年10月25日 18:07:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/74192388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定