go is my first statically typed and compiled language so I am not sure about how to go about doing some things like writing packages...Should I write a package like...
package mypkg
import "fmt"
func mypkg {
fmt.Println("mypackage")
}
and then import this into the main package....install it and then test if it works?
Or should I write mypkg
like this...
package main
import "fmt"
func mypkg() {
fmt.Println("mypackage")
}
func main() {
mypkg()
}
Should I do it this way to make sure that I can call go run mypkg
and see if it works, then delete the main function and rename the package and then work on the rest of the library?
Or did I miss the point entirely and I should do something else?
Here are some basic steps to get you going if you want to use packages.
Create a folder called mypkg
in the folder you're working in. In that folder create a mypkg.go
file with the following code (note the capital letter in the function name. You need to do this so main.go
can see it).
package mypkg
import "fmt"
func Mypkg {
fmt.Println("mypackage")
}
Now install the package just by typing go install
while you're still in your mypkg
directory. This will create a linkable object file you can use.
Now go back to your starting directory and create main.go
with the following code:
package main
import (
"...(path to your mypkg folder)/mypkg"
"fmt"
)
func main() {
mypkg.Mypkg()
//optional
//fmt.Println("whatever")
}
Now run it by typing go run main.go
. This will compile and run main.go
that uses the previous mypkg
package you created.