1. Create a folder "random"
$mkdir random
2. Create a go package called "random" inside the "random" folder. We are going to use 'vim' as our editor in this example. Replace 'vim' with your favorite editor.
$vim random/random.go
3. Paste the following code in it
package random
func FirstName() string {
return "Alice in wonderland"
}
4. Create the file for the main program
$vim names.go
5. Paste the following code in it
package main
import "fmt"
import "./random"
func main() {
n := random.FirstName()
fmt.Println(n)
}
- Note the 'import "./random"' statement which imports the random package which we created above.
- Note the 'package main' statement. Since this is the main file of our program we use 'package main', but in the above 'random/random.go' package we will use 'package random'
- Note how we call the 'random.FirstName()'
6. Now build the program using
$go build names.goThis will automatically compile the random package along with the main program. After running this command you will see a binary executable file called 'names' in the current directory.
$ls names names.go random
7. Run the program
$./names Alice in wonderland
Alternatively you can directly run the program using :
$go run names.go Alice in wonderland