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
You need to do few things
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")
}
The func
keyword is required before main()
statement.
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
}