Function in same package undefined

前端 未结 9 1944
太阳男子
太阳男子 2020-12-28 12:17

My project structure is like this.

packagetest/
    main.go
    lib.go

In main.go, I have this code.

package m         


        
相关标签:
9条回答
  • 2020-12-28 12:45

    This is an old post but it didn't answer my issue clearly, so I'm posting for the benefit of others in the future.

    When run go run --help you will find this manual:

    Run compiles and runs the main package comprising the named Go source files. A Go source file is defined to be a file ending in a literal ".go" suffix.

    By default, 'go run' runs the compiled binary directly: 'a.out arguments...'.

    go run <filename.go> is used for small programs with just a few files. With several files you will run into an issue where your main.go cannot find other files because go run doesn't compile and link them implicitly unless named. That's why go build the project works.

    Alternatively, go run *.go (building all files) should work most of the time.

    0 讨论(0)
  • 2020-12-28 12:45

    You can also try below command if you don't want to build but simply execute it :

    go run main.go lib.go
    
    0 讨论(0)
  • 2020-12-28 12:46

    Try running just go build. When you give it a go file as an argument, it will not look for other go files. You can also do go build *.go

    0 讨论(0)
  • 2020-12-28 12:53
    • lib.go should be renamed to main_test.go
    • The function signature of the test function should be func Test(t *testing.T) {
    • The package testing should be imported in main_test.go.
    • Ideally, the Test function should have a name that reflects what it is testing, like TestPrinting.

    Then both go build and go test should work.

    0 讨论(0)
  • 2020-12-28 12:55

    On the golang.org webpage you can read about the build command that:

    If the arguments are a list of .go files, build treats them as a list of source files specifying a single package.

    So, go build main.go will treat main.go as a single package. Instead, you should use:

    go build
    

    to include all files in the folder.

    0 讨论(0)
  • 2020-12-28 12:56

    I think the problem is you can only have one file using package main.

    Try putting lib.go in a different package. This requires:

    1. lib.go to exist in a folder with the same name as the new package (e.g., myLibs).

    2. Adding the package name to lib.go (package myLibs).

    Then, in main:

    import myLibs
    call myLibs.Test()
    
    0 讨论(0)
提交回复
热议问题