drslez4322 2014-11-14 00:25
浏览 55
已采纳

为什么“执行”命令无法在主软件包中找到第二个文件?

I am experiencing an issue where go run main.go produces the error:

# command-line-arguments
./main.go:9: undefined: test

However the commands go build && ./goruntest compile and run the program just fine.

The output is:

Hi from test()

Hi from sameFileTest()

Hi from pkgtest.Test()

Hi from pkgtest.Test1()

I have the directory set-up like so:

go/src/github.com/username/goruntest/
    pkgtest/
        pkgtest.go
        pkgtest1.go
    main.go
    test2.go

Here is the code.

main.go

package main

import (
    "fmt"
    "github.com/username/goruntest/pkgtest"
)

func main() {
    fmt.Println(test())           // main.go:9
    fmt.Println(sameFileTest())
    fmt.Println(pkgtest.Test())
    fmt.Println(pkgtest.Test1())
}

func sameFileTest() string {
    return "Hi from sameFileTest()"
}

gotest1.go

package main

func test() string {
    return "Hi from test()"
}

pkgtest/pkgtest.go

package pkgtest

func Test() string {
    return "Hi from pkgtest.Test()"
}

pkgtest/pkgtest1.go

package pkgtest

func Test1() string {
    return "Hi from pkgtest.Test1()"
}

I understand that the problem is the second file as part of package main and I also understand that there is no real reason to have a second file in main.

My question is: Why is go run unable to handle this set-up but building and running the executable works just fine?

EDIT

Included a second file in pkgtest

I also understand that the command go run main.go gotest1.go works but why do I need to specify gotest1.go?

I originally omitted these details for the sake of brevity. But now I see they are important to the question.

  • 写回答

1条回答 默认 最新

  • doucaishi0077 2014-11-14 00:41
    关注

    Try providing all relevant files to go run

    $ go help run
    usage: go run [build flags] [-exec xprog] gofiles... [arguments...]
    
    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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测