Go 编程实例【一个目录中多个Go源文件】

一个目录中多个Go源文件

[root@localhost test]# tree
.
├── go.mod
├── helper.go
├── main.go
└── Tcc

0 directories, 4 files
[root@localhost test]# 

要运行一下文件需:

[root@localhost test]# go run main.go
# command-line-arguments
./main.go:9:2: undefined: Myhelper
[root@localhost test]#

有依赖关系所以需要这么运行。

[root@localhost test]# go run main.go helper.go 
Hello, world!
This is a helper function.
[root@localhost test]#

或者编译运行,

[root@localhost test]# ./Tcc 
Hello, world!
This is a helper function.
[root@localhost test]# 

“helper.go” 文件中的代码将被自动链接到可执行文件中,因为它们都在同一个包中。

main.go

package main

import (
	"fmt"
)

func main() {
    
    
	fmt.Println("Hello, world!")
	Myhelper()
}

helper.go

package main

import "fmt"

func Myhelper() {
    
    
	fmt.Println("This is a helper function.")
}

go.mod

module Tcc

go 1.20

引入包的方式

[root@localhost test]# tree
.
├── go.mod
├── helper
│   └── helper.go
└── main.go

1 directory, 3 files
[root@localhost test]#
[root@localhost test]# go run main.go 
Hello, world!
This is a helper function.
[root@localhost test]# 

main.go

package main

import (
	"Tcc/helper"
	"fmt"
)

func main() {
    
    
	fmt.Println("Hello, world!")
	helper.Myhelper()
}

helper/helper.go

package helper

import "fmt"

func Myhelper() {
    
    
	fmt.Println("This is a helper function.")
}

go.mod

module Tcc

go 1.20

猜你喜欢

转载自blog.csdn.net/weiguang102/article/details/130333808
go