drhdjp97757 2018-10-19 05:39
浏览 59
已采纳

如何从Golang中的相邻文件导入代码

Ah yes, the canonical problem when learning a new programming language. I have this:

$GOPATH/
   src/
     huru/
       foo/
          side.go
       hello.go

in hello.go I have:

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)


func main(){
   Foo()
}

and in foo/side.go, I have:

package main

func Foo() {

}

I run:

go install huru

and I get:

# huru
src/huru/hello.go:22:2: undefined: Foo

the compiler doesn't like the Foo() call in hello.go, how do I import it properly? Should I be using package main for both files? Why wouldn't the package be called huru, I assume I should call the package huru..instead of main? idk.

  • 写回答

2条回答 默认 最新

  • duannei0044 2018-10-19 07:21
    关注

    You must not use main as the package name of huru/foo/side.go, because it's already used in the huru/hello.go where the path is different than where side.go located.

    So change the package name on the huru/foo/side.go file. Better to use folder name as the package name.

    package foo
    
    func Foo() {
    
    }
    

    Then on the huru/hello.go, import the huru/foo package so you'll be able to consume the Foo() function that defined on the file inside.

    package main
    
    import (
        "encoding/json"
        "log"
        "net/http"
        "github.com/gorilla/mux"
        "huru/foo" // <------ here
    )
    
    func main(){
       foo.Foo()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试