Go Packages
Go Packages
As an example in our code, we created a file called helper.go in the same main package
helper.go code
package main
import "strings"
func validateUserInput(firstName string, lastName string, email string, userTickets uint) (bool, bool, bool) {
isValidName := len(firstName) >= 2 && len(lastName) >= 2 //true assigned to variable if both the conditions are true
isValidEmail := strings.Contains(email, "@") //if email contains @, it returns true
isValidTicketNumber := userTickets > 0 && userTickets <= remainingTickets
main.go code
package main
import (
"fmt"
"strings"
)
func main() {
greetUsers()
for {
if remainingTickets == 0 {
Go Packages 1
fmt.Println("email does not contain @")
}
if !isValidTicketNumber{
fmt.Println("number of ticket is invalid")
}
}
func greetUsers() {
fmt.Printf("Welcome to %v booking application\n", conferenceName)
fmt.Printf("We have total of %v tickets and %v tickets are left.\n", conferenceTickets, remainingTickets)
fmt.Println("Get your tickets here to attend")
}
func printFirstNames(){
firstNames := []string{}
for _, booking := range bookings {
var names = strings.Fields(booking)
firstNames = append(firstNames, names[0])
}
Now to run the program, the command is not same, use different command.
$ go run .
This command will run all the files in the current folder.
Go Packages 2
To make a different package, we create a folder for that package. As an example in our code for helper.
Now in the main.go, the validateUserInput() function is not defined because now it does not belong to the same package.
Import the package in main and export the function from other file.
//Import
import (
"go-booking-app/helper" //go-booking-app is the main module name defined in go.mod
)
//export
Go Packages 3
Go Packages 4