代码之家  ›  专栏  ›  技术社区  ›  clay

其他文件中的go+goland调用函数

  •  1
  • clay  · 技术社区  · 6 年前

    目录布局:

    ~ cd $GOPATH
    ~ tree src/simple 
    src/simple
    └── main
        ├── main.go
        └── other.go
    

    Mun.Go:

    package main
    
    import "fmt"
    
    func main() {
        fmt.Println("This is in main. calling somefunc...")
        somefunc()
        fmt.Println("done. bye :)")
    }
    

    Go:

    package main
    
    import "fmt"
    
    func somefunc() {
        fmt.Println("This is in somefunc in other.go")
    }
    

    这个很好用 go build :

    ~ cd $GOPATH/src/simple/main/
    ~ go build
    ~ ./main
    This is in main. calling somefunc...
    This is in somefunc in other.go
    done. bye :)
    

    从戈兰区内部,如果我跑步,我会得到:

    main/main.go:7:2: undefined: somefunc
    

    通常,编辑器会突出显示所有语法错误。这个 somefunc 在编辑器中,调用被视为有效语法,但当我运行时,它不起作用。我甚至可以按Cmd,点击函数跳转到定义。

    这是与戈兰2018.2.3和 go version go1.11

    1 回复  |  直到 6 年前
        1
  •  2
  •   peterm    6 年前

    在戈兰创建一个运行配置 Run -> Edit Configurations 基于 Go Build 模板和设置

    Name: Build (or whatever you like)
    Run kind: Directory
    Directory: /Users/gopher/go/src/simple/main/
                                          ^^^^^^
    Run after build: checked
    Working directory: /Users/gopher/go/src/simple
    

    变化 /Users/gopher/go/ 相应的部分,以匹配您的实际路径 $GOPATH

    然后 Run -> Build 项目

    This is in main. calling somefunc...
    This is in somefunc in other.go
    done. bye :)
    
    Process finished with exit code 0