[英]Opening a go file inside another go program
I am learning Go using "The Go Programming Language" book.我正在使用“Go 编程语言”书学习 Go。 First chapter introduced
os.Open
module for reading files.第一章介绍了用于读取文件的
os.Open
模块。 I tried opening a go file like below.我尝试打开 go 文件,如下所示。
f, err = os.Open("helloworld.go")
I got following error:我收到以下错误:
# command-line-arguments
.\helloworld.go:6:6: main redeclared in this block
previous declaration at .\dup2.go:10:6
I want to understand why go behaved as if it's trying to compile the file instead of reading like other languages ( Python, Java or C) do.我想了解为什么 go 表现得好像它正在尝试编译文件而不是像其他语言一样读取(Python、Java 或 C)。
What is the correct way of opening a file?打开文件的正确方法是什么?
The error you got indicate that you have 2 main()
function in the same package.您收到的错误表明您在同一个 package 中有 2 个
main()
function。
A package can have many files. package 可以有很多文件。 When you have multiple
.go
files in the same directory that you run go build
command in, the compiler will build the main
package.当您在运行
go build
命令的同一目录中有多个.go
文件时,编译器将构建main
package。 In this case, it detected duplicated main()
function hence the build failed.在这种情况下,它检测到重复的
main()
function 因此构建失败。
What you want to do is specify which file you want to build:您要做的是指定要构建的文件:
go build helloworld.go
With the file specified, go build
will only build with the file(s) you have listed.指定文件后,
go build
将仅使用您列出的文件进行构建。
For more information on go build
you can refer to Golang Documentation .有关
go build
的更多信息,您可以参考Golang 文档。
Though you shouldn't do it but technically you can read a '.go' file with main() from another.go file.尽管您不应该这样做,但从技术上讲,您可以从另一个.go 文件中读取带有 main() 的“.go”文件。 Your case is failing as you are building a package having multiple files defining main.
您的案例失败,因为您正在构建一个 package 具有多个定义 main.
Again clarifying, it is discouraged to have multiple files with main in the same package, and it will fail when you build the package.再次澄清,不鼓励在同一个 package 中拥有多个 main 文件,并且在构建 package 时它将失败。 This is so, as there should be just one entry point (main() function) in the package.
之所以如此,是因为 package 中应该只有一个入口点(main() 函数)。
Coming to technicality, you can read a go file from another in same package, but in this case you need to build just the file (not the whole package).谈到技术性,您可以从同一个 package 中的另一个文件中读取 go 文件,但在这种情况下,您只需要构建文件(而不是整个包)。 Alternately you can issue go run
或者,您可以发出 go 运行
$ cat main1.go
package main
import "fmt"
func main() {
fmt.Println("Hello")
}
$
$ cat readinfolder.go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
filehandle, err := os.Open("main1.go")
if err != nil {
panic(err)
}
defer filehandle.Close()
scanner := bufio.NewScanner(filehandle)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
$
$
$ go build readinfolder.go
$ ./readinfolder
package main
import "fmt"
func main() {
fmt.Println("Hello")
}
$
I'll show you how I've read files into a Directory.我将向您展示我是如何将文件读入目录的。
1: You should make the package and import tools:
2: Make new structs for Files and Directories.
3: Make some functions to read new files.
4: Execute your tasks in main function
5: Use ioutil.ReadFile function to read some file
Directory tree目录树
.
|____main.go
|____files
| |____example2.txt
| |____example1.txt
Example code:示例代码:
package main
import (
"fmt"
"io/ioutil"
"log"
)
// Define Directory struct
type Directory struct {
Path string
Files []File
}
// Define File struct
type File struct {
Name string
}
// Function to return path
func (this Directory) getPath() string {
return this.Path
}
// Function to set a path
func (this Directory) setPath(path string) string {
this.Path = path
return this.Path
}
// Function to get fies into a directory
func (this Directory) getFiles(path string) []File {
directory, err := ioutil.ReadDir(path)
if err != nil {
log.Fatal(err)
}
for _, f := range directory {
this.Files = append(this.Files, File{Name: f.Name()})
}
return this.Files
}
//Main function
func main() {
// Set variables
dir := new(Directory)
path := dir.setPath("/home/your_user/your_project_folder/files/")
files := dir.getFiles(path)
firstFiles := dir.getFiles(path)[0].Name
//Read File
f, err := ioutil.ReadFile("/home/your_user/your_project_folder/files/" + firstFiles)
if err != nil {
log.Fatal(err)
}
// Print results
fmt.Println(files)
fmt.Println(firstFiles)
fmt.Println(string(f))
}
output: output:
[{example1.txt} {example2.txt}]
example1.txt
some text in file!
Finally: You should do go build
, to build the project as a binary.最后:您应该执行
go build
,将项目构建为二进制文件。
I hope this example may help you to understand better how golang works我希望这个例子可以帮助你更好地理解 golang 是如何工作的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.