dongqianzhan8325 2019-07-27 04:06
浏览 69
已采纳

为什么我的包裹中的功能无法正常工作

I have put a small code file in $GOPATH which is ~/go/src. Here I have made a folder mysrc and there I have kept a file mytest.go, which is as follows:

package mytest
import ("fmt")
func myfn(){
  fmt.Println("My own fn")
}

I try to import above code with following file:

package main
import ("mysrc")
main(){
    myfn()
}

When I try to run above file, I get error:

# command-line-arguments
./useMyfn.go:3:1: syntax error: non-declaration statement outside function body

Where is the problem and how can it be solved? Thanks for your help.

Edit: I corrected the main fn to func main() but now the errors are:

# command-line-arguments
./useMyfn.go:2:9: imported and not used: "mysrc" as mytest
./useMyfn.go:4:2: undefined: myfn
  • 写回答

1条回答 默认 最新

  • douye1876 2019-07-27 05:17
    关注

    You need to do few things

    1. I suggest to use a package name that the name is same with the folder name.
    2. The myfn() function need to be exported. How to do it: simply set the first character of the function name to uppercase.
    package mysrc // <-- 1
    
    import (
        "fmt"
    )
    
    func Myfn() { // <-- 2
        fmt.Println("My own fn")
    }
    
    1. The func keyword is required before main() statement.

    2. To access a function from other package, you need to write down the package name before the function name. In this context it'll be mysrc.Myfn().

    package main
    
    import (
        "mysrc"
    )
    
    func main() { // <-- 3
        mysrc.Myfn() // <-- 4
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端