簡體   English   中英

在另一個 go 程序中打開 go 文件

[英]Opening a go file inside another go program

我正在使用“Go 編程語言”書學習 Go。 第一章介紹了用於讀取文件的os.Open模塊。 我嘗試打開 go 文件,如下所示。

  f, err = os.Open("helloworld.go")

我收到以下錯誤:

   # command-line-arguments
.\helloworld.go:6:6: main redeclared in this block
        previous declaration at .\dup2.go:10:6

我想了解為什么 go 表現得好像它正在嘗試編譯文件而不是像其他語言一樣讀取(Python、Java 或 C)。

打開文件的正確方法是什么?

您收到的錯誤表明您在同一個 package 中有 2 個main() function。
package 可以有很多文件。 當您在運行go build命令的同一目錄中有多個.go文件時,編譯器將構建main package。 在這種情況下,它檢測到重復的main() function 因此構建失敗。

您要做的是指定要構建的文件:

go build helloworld.go

指定文件后, go build將僅使用您列出的文件進行構建。

有關go build的更多信息,您可以參考Golang 文檔

盡管您不應該這樣做,但從技術上講,您可以從另一個.go 文件中讀取帶有 main() 的“.go”文件。 您的案例失敗,因為您正在構建一個 package 具有多個定義 main.

再次澄清,不鼓勵在同一個 package 中擁有多個 main 文件,並且在構建 package 時它將失敗。 之所以如此,是因為 package 中應該只有一個入口點(main() 函數)。

談到技術性,您可以從同一個 package 中的另一個文件中讀取 go 文件,但在這種情況下,您只需要構建文件(而不是整個包)。 或者,您可以發出 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")
}
$ 


我將向您展示我是如何將文件讀入目錄的。

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

目錄樹

.
|____main.go
|____files
| |____example2.txt
| |____example1.txt

示例代碼:

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:

[{example1.txt} {example2.txt}]
example1.txt
some text in file!

最后:您應該執行go build ,將項目構建為二進制文件。

我希望這個例子可以幫助你更好地理解 golang 是如何工作的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM