Background
Let us go with a simple hellowWorld sample applications.
Exercise – helloWorld
Outline
- package
- package main
- Main Routine
- package main
- import
- List packages to import
- fmt
- List packages to import
- Functions
- main
- Print messages using fmt.Println
- print “hello world“
- Print messages using fmt.Println
- main
Code
package main import "fmt" func main(){ fmt.Println("hello world") }
Run
Invoke
go run helloWorld_01.go
Output
Output – Image
Output – Text
>go run helloWorld_01.go hello world
Exercise – helloWorldPersonalize
Outline
- package
- package main
- Main Routine
- package main
- import
- List packages to import
- fmt
- os/user
- strings
- List packages to import
- Functions
- stringIsEmpty
- Determine if string is empty
- Trim String
- Checked trimmed strings length against 0
- Determine if string is empty
- displayHello
- Access user object
- Get user.Current
- Place value in objUser
- Place error in objError variable
- If objError
- Display error
- Exit Function
- Get user.Current
- Print messages using fmt.Println
- print “hello world”
- print name ( objUser.Name )
- print username ( objUser.username )
- Access user object
- stringIsEmpty
Code
package main import ( "fmt" "os/user" "strings" ) /* What is the best way to test for an empty string in Go? https://stackoverflow.com/questions/18594330/what-is-the-best-way-to-test-for-an-empty-string-in-go */ func stringIsEmpty(s string) bool { return len(strings.TrimSpace(s)) == 0 } func displayHello(){ /* Declare Variables objUser as pointer (*) to user.User */ var objUser *user.User var strFormattedName string var strBuffer string var objError error /* Get current user by accessing the user object https://golang.org/pkg/os/user/ Imported Module os/user */ objUser, objError = user.Current() if objError!= nil { strBuffer = fmt.Sprintf( "Failed to properly access the %s module\n", "user.Current") fmt.Println(strBuffer); panic(objError) } strFormattedName = ""; /* If Name is indicated */ if (stringIsEmpty(objUser.Name) == false) { strFormattedName = objUser.Name; if (objUser.Username != "") { strFormattedName = strFormattedName + " (" + objUser.Username + " )"; } } else { if (stringIsEmpty(objUser.Username) == false) { if (strFormattedName == ""){ strFormattedName = objUser.Username; }else { strFormattedName = strFormattedName + " (" + objUser.Username + " )"; } } } strBuffer = fmt.Sprintf("Hi %s\n" , strFormattedName); fmt.Println(strBuffer); } func main(){ displayHello() }
Run
Invoke
go run helloWorldPersonalize_01.go
Output
Output – Image
Output – Text
Hi LAB\dadeniji
Source Code Control
Github
References