简体   繁体   English

如何用go语言从另一个文件调用函数?

[英]How to call function from another file in go language?

I want to call function from another file in go lang, can any one help?我想从 go lang 中的另一个文件调用函数,有人可以帮忙吗?

test1.go

package main

func main() {
    demo()
}

test2.go

package main

import "fmt"

func main() {
}

func demo() {
    fmt.Println("HI")
}

How to call demo in test2 from test1 ?如何从test1调用test2 demo

You can't have more than one main in your package.您的包裹中最多只能有一个main

More generally, you can't have more than one function with a given name in a package.更一般地说,一个包中不能有多个具有给定名称的函数。

Remove the main in test2.go and compile the application.拆下maintest2.go和编译应用程序。 The demo function will be visible from test1.go . demo功能将从test1.go可见。

Go Lang by default builds/runs only the mentioned file.默认情况下,Go Lang 仅构建/运行提到的文件。 To Link all files you need to specify the name of all files while running.要链接所有文件,您需要在运行时指定所有文件的名称。

Run either of below two commands:运行以下两个命令之一:

$go run test1.go test2.go. //order of file doesn't matter
$go run *.go

You should do similar thing, if you want to build them.如果你想构建它们,你应该做类似的事情。

I was looking for the same thing.我正在寻找同样的东西。 To answer your question " How to call demo in test2 from test1? ", here is the way I did it.要回答您的问题“如何从 test1 调用 test2 中的演示? ”,这是我的方法。 Run this code with go run test1.go command.使用go run test1.go命令运行此代码。 Change the current_folder to folder where test1.go is.current_folder更改为 test1.go 所在的文件夹

test1.go test1.go

package main

import (
    L "./lib"
)

func main() {
    L.Demo()
}

lib\\test2.go lib\\test2.go

Put test2.go file in subfolder lib将 test2.go 文件放在子文件夹lib

package lib

import "fmt"

// This func must be Exported, Capitalized, and comment added.
func Demo() {
    fmt.Println("HI")
}

If you just run go run test1.go and that file has a reference to a function in another file within the same package, it will error because you didn't tell Go to run the whole package, you told it to only run that one file.如果您只运行go run test1.go并且该文件引用了同一包内另一个文件中的函数,则会出错,因为您没有告诉 Go 运行整个包,而是告诉它只运行那个包文件。

You can tell go to run as a whole package by grouping the files as a package in the run commaned in several ways.您可以通过多种方式在运行中将文件分组为一个包来告诉 go 作为一个完整的包运行。 Here are some examples (if your terminal is in the directory of your package):以下是一些示例(如果您的终端在您的包目录中):

go run ./

OR要么

go run test1.go test2.go

OR要么

go run *.go

You can expect the same behavior using the build command, and after running the executable created will run as a grouped package, where the files know about eachothers functions, etc. Example:您可以使用 build 命令预期相同的行为,并且在运行后创建的可执行文件将作为分组包运行,其中文件知道彼此的功能等。 示例:

go build ./

OR要么

go build test1.go test2.go

OR要么

go build *.go

And then afterward simply calling the executable from the command line will give you a similar output to using the run command when you ran all the files together as a whole package.然后,当您将所有文件作为一个完整的包一起运行时,只需从命令行调用可执行文件就会为您提供与使用 run 命令类似的输出。 Ex:前任:

./test1

Or whatever your executable filename happens to be called when it was created.或者无论您的可执行文件名在创建时碰巧被调用。

Folder Structure

duplicate
  |
  |--duplicate_main.go
  |
  |--countLines.go
  |
  |--abc.txt

duplicate_main.go复制_main.go

    package main

    import (
        "fmt"
        "os"
    )

    func main() {
        counts := make(map[string]int)
        files := os.Args[1:]
        if len(files) == 0 {
            countLines(os.Stdin, counts)
        } else {
            for _, arg := range files {
                f, err := os.Open(arg)
                if err != nil {
                    fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
                    continue
                }
                countLines(f, counts)
                f.Close()
            }
        }

        for line, n := range counts {
            if n > 1 {
                fmt.Printf("%d\t%s\n", n, line)
            }
        }
    }

countLines.go countLines.go

    package main

    import (
        "bufio"
        "os"
    )

    func countLines(f *os.File, counts map[string]int) {
        input := bufio.NewScanner(f)
        for input.Scan() {
            counts[input.Text()]++
        }
    }
  1. go run ch1_dup2.go countLines.go abc.txt
  2. go run *.go abc.txt
  3. go build ./
  4. go build ch1_dup2.go countLines.go
  5. go build *.go

A functional, objective, simple quick example:一个功能性的、客观的、简单的快速示例:

main.go main.go

package main

import "pathToProject/controllers"

func main() {
    controllers.Test()
}

control.go control.go

package controllers

func Test() {
// Do Something
}

Don't ever forget: Visible External Functions, Variables and Methods starts with Capital Letter.永远不要忘记:可见的外部函数、变量和方法以大写字母开头。

ie: IE:

func test() {
    // I am not Visible outside the file
}
 
func Test() {
    // I am VISIBLE OUTSIDE the FILE
}

You can import functions from another file by declaring the other file as a module.您可以通过将另一个文件声明为模块来从另一个文件导入函数。 Keep both the files in the same project folder.将这两个文件保存在同一个项目文件夹中。 The first file test1.go should look like this:第一个文件test1.go应如下所示:

package main

func main() {
    demo()
}

From the second file remove the main function because only one main function can exist in a package.从第二个文件中删除 main 函数,因为一个包中只能存在一个 main 函数。 The second file, test2.go should look like below:第二个文件test2.go应如下所示:

package main

import "fmt"

func demo() {
    fmt.Println("HI")
}

Now from any terminal with the project directory set as the working directory run the command: go mod init myproject .现在从任何将项目目录设置为工作目录的终端运行命令: go mod init myproject This would create a file called go.mod in the project directory.这将在项目目录中创建一个名为go.mod的文件。 The contents of this mod file might look like the below:mod文件的内容可能如下所示:

module myproject

go 1.16

Now from the terminal simply run the command go run .现在从终端只需运行命令go run . ! The demo function would be executed from the first file as desired !!演示功能将根据需要从第一个文件执行!!

as a stupid person who didn't find out what is going on with go module should say :作为一个没有发现 go 模块发生了什么的愚蠢的人应该说:

  1. create your main.go创建你的 main.go
  2. in the same directory write this in your terminal在同一目录中,将其写入您的终端中

go mod init "your module name" go mod init“你的模块名称”

  1. create a new directory and go inside it创建一个新目录并进入其中
  2. create a new .go file and write the directory's name as package name创建一个新的 .go 文件并将目录名写入包名
  3. write any function you want ;编写任何你想要的函数; just notice your function must starts with capital letter请注意您的函数必须以大写字母开头
  4. back to main.go and回到 main.go 和

import "your module name / the name of your new directory"导入“您的模块名称/新目录的名称”

  1. finally what you need is writing the name of package and your function name after it最后你需要的是在它后面写包名和你的函数名

"the name of your new dirctory" + . “您的新目录的名称” + . + YourFunction() + 你的功能()

  1. and write this in terminal并在终端中写下这个

go run .去跑步 。

you can write go run main.go instead.你可以写go run main.go来代替。 sometimes you don't want to create a directory and want to create new .go file in the same directory, in this situation you need to be aware of, it doesn't matter to start your function with capital letter or not and you should run all .go files有时您不想创建目录而想在同一目录中创建新的 .go 文件,在这种情况下您需要注意,无论是否以大写字母开头都没有关系,您应该运行所有 .go 文件

go run *.go去跑 *.go

because因为

go run main.go去运行 main.go

doesn't work.不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM