| by Arround The Web | No comments

30 Golang programming examples for beginners

Golang which is also called Go programming language is an open-source programming language designed by Google in 2007. Version 1.0 of this language was released in 2012. It is a structured programming language like C and different types of applications such as networking services, cloud applications, web applications, etc. can be developed by Golang language. It contains many types of packages like Python. It is very easy to learn, which makes this language popular for new programmers. 30 Golang programming examples have been explained in this tutorial to learn Golang from the basics.

Pre-requisites:

Golang is supported by different types of operating systems. The way of installing Golang on Ubuntu has been shown in this part of the tutorial. Run the following commands to update the system and install the Golang on the system before practicing the examples in this tutorial.

$ sudo apt update
$ sudo apt install golang-go

Run the following command to check the installed version of the Golang.

$ go version

Table of contents:

  1. Golang hello world
  2. Golang string variables
  3. Golang int to string
  4. Golang string to int
  5. Golang string concatenation
  6. Golang multiline string
  7. Golang split string
  8. Golang sprintf
  9. Golang enum
  10. Golang struct
  11. Golang array
  12. Golang set
  13. Golang for loop
  14. Golang for range
  15. Golang while loop
  16. Golang continue
  17. Golang switch case
  18. Golang random number
  19. Golang sleep
  20. Golang time
  21. Golang uuid
  22. Golang read file
  23. Golang read file line by line
  24. Golang write to file
  25. Golang check if file exists
  26. Golang csv
  27. Golang yaml
  28. Golang http request
  29. Golang command line arguments
  30. Golang error handling


Golang hello world

The main package of Golang contains all required packages for Golang programming and it is required to start the execution of the Golang script. The fmt package is required to import for printing the formatted string in the terminal. Create a Golang file with the following script. The string value, ‘Hello World.’ will be printed in the terminal after executing the script.

//Import the fmt package to print the output
import "fmt"

//Define the main() function to start the execution
func main() {

//Print a simple message with the new line
fmt.Println("Hello World.")

}

Run the following command to execute the script. Here, the script has been saved in the example1, go file.

$ go run example1.go

Run the following command to build the binary file of the Golang file.

$ go build example1.go

Run the following command to run the executable file.

$ ./example1

The following output will appear after executing the above commands,,

p1

Go to top


Golang string variables

The string variables can be used without defining the data type and with the data type in Golang. Create a Golang file with the following script that will print simple string data and the string data with the string variables. The uses of Printf() and Println() functions have been shown in the script.

package main
//Import the fmt package to print the output
import "fmt"

//Define the main() function
func main() {

  //Print a string value with a new line
  fmt.Printf("Learn Golang from LinuxHint.com.\n")

  //Define the first string variable
  var str1 = "Golang Programming. "

  //Print the variable without a newline
  fmt.Printf("Learn %s", str1)

  //Define the second string variable
  var str2 = "easy to learn."

  //Print the variable with a newline
  fmt.Println("It is", str2)
}

The following output will appear after executing the above script. The output of the two concatenated strings are printed here.

p2

Go to top


Golang int to string

The strconv.Itoa() and strconv.FormatInt() functions can be used to convert the integer to a string value in Golang. The strconv.Itoa() is used to convert the integer value into a string of numbers. The strconv.FormatInt() function is used to convert decimal-based integer values into the string. Create a Golang file with the following script that shows the way of converting the integer to a string in Golang by using the functions mentioned above. A number will be taken from the user and the corresponding string value of the number will be printed as the output.

//Add the main package
package main
//Import the fmt and strconv packages
import (
  "fmt"
  "strconv"
)

//Define the main function
func main()  {

  //Declare an integer variable
  var n int
  //Print a message
  fmt.Printf("Enter a number: ")
  //Take input from the user
  fmt.Scan(&n)

  //Convert integer to string using Itoa() function
  convert1 := strconv.Itoa(n)
  fmt.Printf("Converting integer to string using Itoa(): %s\n", convert1)

  //Convert integer to string using FormatInt() function
  convert2 := strconv.FormatInt(int64(n), 10)
  fmt.Printf("Converting integer to string using FormatInt(): %s\n", convert2)
}

The following output will appear after executing the script. The number. 45 has been converted to the string. “45”.

p3

Go to top


Golang string to int

The strconv.Atoi() function is used to convert the string to an integer in Golang. It takes a string value that will be converted into an integer and returns two types of values. One value is the integer if the conversation is successful and another value is the error if the conversation is unsuccessful otherwise nil value will be returned. Create a Golang file with the following script that will convert a number of string values into an integer by using strconv.Atoi() function. The string value, “342” will be converted into 342 number and printed after the execution.

//Add the main package
package main
//Import the fmt and strconv packages
import (
  "fmt"
  "strconv"
)

//Define the main function
func main()  {

  //Declare a string variable
  str := "342"

  //Convert string to integer using Atoi() function
  price, err := strconv.Atoi(str)

  //check for error
  if err == nil {
    //Print the converted value
    fmt.Printf("The price of the book is %d\n", price)
  }else{
    //Print the error message
    fmt.Println(err)
  }
}

The following output will appear after executing the script. The string value, “342” has been converted to 342 here.

p4

Go to top


Golang string concatenation

Create a Golang file with the following script that will concatenate the strings with the ‘+’ operator by using the Printf() function. The Println() function has been used here to print the concatenated string value by using the ‘+’ operator and Printf() function has been used here to print the concatenated string value by using the ‘%s’ specifier. Two string variables have been declared in the script which are concatenated later.

//Add the main package
package main
//Import the fmt package to print the output
import "fmt"

//Define the main function
func main() {

   //Declare two string variables
   var str1, str2 string

   //Assign string values
   str1 = " Golang"
   str2 = " Programming"

   //Concatenating string using '+' operator
   fmt.Println("Concatenated string value using '+' operator:", str1 + str2)
   //Concatenating string using '%s' specifier
   fmt.Printf("Concatenated string value using format specifier: %s%s\n", str1, str2)
}

The following output will appear after executing the script.

p5

Go to top


Golang multi-line string

Three different ways have been shown in the following example to print the multi-line text by using the Golang script. The ‘\n’ character has been used in the first string variable to generate the multi-line text. The backticks (`) have been used in the second string to print the multi-line text. The backticks (`) with specifiers have been used in the third string to print multi-line text.

package main
//Import the fmt package
import "fmt"

//Define the main function
func main() {

   //Declare a multi-line string value with '\n' character
   str1 := "Golang programming\is very easy\nto learn.\n\n"
   fmt.Printf(str1)

   //Declare a multi-line string value with backticks(`)
   str2 := `Learn
Golang
from
LinuxHint
Blog.`

   fmt.Printf("%s\n\n",str2)

   //Declare two string values
   language := "Golang"
   developer := "Google"
   //Declare a string value with variables and backticks
   str3 := `%s
is
developed
by
%s.`

   fmt.Printf(str3, language, developer)
   //Add a new line
   fmt.Println()
}

The following output will appear after executing the script. The output of the three string variables that contain multi-line string values has been printed here.

p6

Go to top


Golang split string

The strings.Split() function has been used to split the string data based on the separator. The following script will take a string value from the user and split the string value based on the colon(:). The total number of split values and the first two split values will be printed after the execution.

package main
//Import the fmt and strings packages
import (
  "fmt"
  "strings"
)

//Define the main function
func main() {

    //Declare a string variable
    var str string
    //Print a prompt message
    fmt.Printf("Enter a string with colon(:)- ")
    //Take input from the user
    fmt.Scan(&str)

    //Define the separator
    separator := ":"
    //Split the string value
    split_value := strings.Split(str, separator)
    //Count the number of split values
    length := len(split_value)

    //Print the number of split values
    fmt.Printf("Total number of split values is %d\n", length)
    //Print the split values
    fmt.Println("The first split value is", split_value[0])
    fmt.Println("The second split value is", split_value[1])
}

The following output will appear after executing the script. The input value, “golang:google” has been divided into two parts based on the colon(:).

p7

Go to top


Golang sprintf

The Sprintf() function is used in Golang to store the formatted string values into a variable like other standard programming languages. A string and an integer variable have been declared in the following script. The values of these variables have been formatted and stored into a variable by using the Sprintf() function.

package main
//Import the fmt package
import "fmt"

//Define the main function
func main() {

  //Declare two variables
  var str string
  var num int

  //Assign string value
  str = "Golang"
  //Assign number value
  num = 2012

  //Store the combined string value in a variable
  combined_str := fmt.Sprintf("The first version of %s is released in %d.", str, num)
  //Print the variable
  fmt.Printf("The output of the Sprintf(): \n%s\n", combined_str)
}

The following output will appear after executing the script.

p8

Go to top


Golang enum

The enum or enumerator has been used in Golang to declare a data type of a group of related constant values. The declaration of enum type in Golang is different from other programming languages. An enum type of 12 values has been declared and the numeric value of the particular enum value has been printed later.

package main
//Import the fmt package
import "fmt"

//Declare the type to store the month value in number (1-12)
type Month int

//Declare constants for each month's value starting from 1
const (
  Jan Month = iota + 1
  Feb
  Mar
  Apr
  May
  Jun
  Jul
  Aug
  Sep
  Oct
  Nov
  Dec
)

//Declare main function
func main() {
    //Declare variable with a month value
    var M_num = May
    //Print the corresponding number value of the month
    fmt.Println("The month value in number is ", M_num)
}

The following output will appear after executing the script. The corresponding numeric value of the May is 5.

p9

Go to top


Golang struct

The struct or structure is used in Golang to declare a type that contains different types of variables. It is useful for storing tabular data or multiple records. In the following script, a structure variable of four elements has been declared. Next, two records have been added by using the defined struct variable. The way of printing the values of the struct in different ways has been shown in the last part of the script.

package main
//Import fmt package
import "fmt"

//Define a structure of four elements
type Product struct {
    id      string
    name    string
    size    string
    price   int
}

func main() {

    //Declare the first structure variable
    product1 := Product {"p-1209", "HDD", "5TB", 80}
    //Declare the second structure variable
    product2 := Product {"p-7342", "Mouse", "", 15}

    //Print the structure variables
    fmt.Println("First product: ", product1)
    fmt.Println("Second product: ", product2)

    //Print four values of the first structure variable separately
    fmt.Println("First product details:")
    fmt.Println("ID: ",product1.id)
    fmt.Println("Name: ",product1.name)
    fmt.Println("Size: ",product1.size)
    fmt.Println("Price: ",product1.price)
}

The following output will appear after executing the script.

p10

Go to top


Golang array

The array variable is used in Golang to store multiple values of the particular data type like other standard programming languages. The way of declaring and accessing an array of string values and an array of numeric values has been shown in the script.

package main
//Import fmt package
import "fmt"

func main() {

   //Declare an array of string values
   str_arr := [4] string {"google.com", "ask.com", "bing.com", "you.com"}
   //Print the array of string
   fmt.Println("String Array values are: ", str_arr)
   //Print the 3rd element of the array
   fmt.Println("The 3rd value of array is", str_arr[2])

   //Declare an array of numeric values
   int_arr := [6]int{65, 34, 12, 81, 52, 70}
   //Print the array of integer
   fmt.Println("Integer Array values are: ", int_arr)
   //Print the 4th element of the array
   fmt.Println("The 4th value of array is", int_arr[3])
}

The following output will appear after executing the script.

p11

Go to top


Golang set

The set is another data structure of Golang to store a collection of distinct values. It is used to store unique values in an object. Golang has no built-in set data structure like other programming languages. But this feature can be implemented by using empty struct{} and map. In the following script, a set variable of strings has been declared by using a map with the empty struct. Next, three values have been added, one value has been deleted, and one value has been added again in the set. The values of the set have been printed together and separately.

package main
//Import fmt package
import "fmt"

func main() {
   //Define a set of strings
   lang := map[string]struct{}{}
   //Insert three elements into the set using an empty struct
   lang["Go"] = struct{}{}
   lang["Bash"] = struct{}{}
   lang["Python"] = struct{}{}

   //Print the current existing elements of the set
   fmt.Println(lang)

   //Remove an element from the set
   delete(lang, "Python")

   //Add a new element to the set
   lang["Java"] = struct{}{}

   //Print the set values after removing and adding an element
   fmt.Println(lang)

   fmt.Printf("\nSet values are:\n")
   //Print each element of the set separately
   for l := range lang {
      fmt.Println(l)
   }
}

The following output will appear after executing the script.

p12

Go to top


Golang for loop

The for loop can be used in different ways and for different purposes in Golang. The use of three expressions for loop has been shown in the following script. The loop will be iterated 5 times to take 5 input values and the sum of these input values will be printed later.

package main
//Import fmt package
import "fmt"

func main() {

  //Declare an integer variable
  var number int
  //Declare a variable to store the sum value
  var sum = 0
  //Define a for loop
  for n := 1; n <= 5; n++ {
    //Print a prompt message
    fmt.Printf("Enter a number:")
    //Take input from the user
    fmt.Scan(&number)
    //Add the input number with the sum variable
    sum = sum + number
  }
  //Print the summation result
  fmt.Printf("The sum of five input values is %d\n", sum)

}

The following output will appear after executing the script. The sum of 6, 3, 4, 7, and 9 is 29.

p13

Go to top


Golang for range

The range is used with the for loop in the Golang to access string, array, and map. The way of accessing an array of strings by using a for loop with range has been shown in the following script. The first for loop will print the array values only and the second for loop will print the indexes and values of the array.

package main
//Import fmt package
import "fmt"

func main() {

  //Declare an array of string
  flowers := [4] string {"Rose", "Lily", "Dalia", "Sun Flower"}

  fmt.Println("Array values are:")
  //Print the array values
  for _, val := range flowers {
    fmt.Println(val)
  }

  fmt.Println("Array indexes and values are:")
  //Print the array values based on index
  for in, val := range flowers {
    fmt.Printf("%d := %s\n", in + 1, val)
  }
}

The following output will appear after executing the script.

p14

Go to top


Golang while loop

Golang has no while loop like other programming languages. However, the feature of the while loop can be implemented in Golang by using the for loop. The way of implementing a while loop by using a for loop has been shown in the following script. The for loop will be iterated for 4 times and take four numbers. The sum of these numbers with the fractional value will be printed later.

package main
//Import fmt package
import "fmt"

func main() {
  counter := 1
  sum := 0.0
  var number float64
  for counter <= 4 {
    //Print a prompt message
    fmt.Printf("Enter a number: ")
    //Take input from the user
    fmt.Scan(&number)
    //Add the input number with the sum variable
    sum = sum + number
    //Increment the counter by 1
    counter++
  }
  //Print the summation result
  fmt.Printf("The sum of four input values is %0.2f\n", sum)
}

The following output will appear after executing the script. The sum of 6.8, 3.2, 8.5, and 4.9 is 23.40.

p15

Go to top


Golang continue

The continue statement is used in any loop to omit the particular statements based on a condition. In the following script, the for loop has been used to iterate the loop that will omit the values of the 2nd and the fourth values of the array by using the continue statement.

package main
//Import fmt package
import "fmt"

func main() {
  counter := 1
  sum := 0.0
  var number float64
  for counter <= 4 {
    //Print a prompt message
    fmt.Printf("Enter a number: ")
    //Take input from the user
    fmt.Scan(&number)
    //Add the input number with the sum variable
    sum = sum + number
    //Increment the counter by 1
    counter++
  }
  //Print the summation result
  fmt.Printf("The sum of four input values is %0.2f\n", sum)
}

The following output will appear after executing the script.

p16

Go to top


Golang switch case

The switch-case statement in Golang is similar to the other programming languages but no break statement is required with each case statement in Golang. The way of defining multiple case values inside the switch block has been shown in the following example.

package main
//Import fmt package
import "fmt"

func main() {

   var n int
   //Print a prompt message
   fmt.Printf("Enter the month value in number: ")
   //Take input from the user
   fmt.Scan(&n)

   //Print message based on the matching case value
   switch n {
    case 1, 2, 3, 4:
      fmt.Println("Winter semester.")

    case 5, 6, 7, 8:
      fmt.Println("Summer semester.")

    case 9, 10, 11, 12:
      fmt.Println("Fall Semester.")

    default:
      fmt.Println("Month value is out of range.")
   }
}

The following output will appear after executing the script.

p17

Go to top


Golang random number

The math/rand package has been used in Golang to generate random numbers. The way of generating four types of random numbers has been shown in the following script. The rand.Int() function is used to generate a long integer random number. The rand.Intn(n) function is used to generate an integer random number of the particular range and the highest value will be passed as the argument value of the function. The 999 is set as the argument value in the script. The rand.Float32() function is used to generate a short fractional random number and the rand.Float64() function is used to generate a long fractional random number.

//Add main package
package main
//Import required modules
import (
  "fmt"
  "time"
  "math/rand"
)

func main() {
  //Set seed to generate a random number
  rand.Seed(time.Now().UnixNano())
  //Print generated random integer
  fmt.Println("Random integer value: ", rand.Int())
  //Print the random integer within 999
  fmt.Println("Random integer value with range: ", rand.Intn(999))
  //Print the random 32 bits float
  fmt.Println("Random 32 bits float value: ", rand.Float32())
  //Print the random 64 bits float
  fmt.Println("Random 64 bits float value: ", rand.Float64())
}

The following output will appear after executing the script.

p18

Go to top


Golang sleep

The time.Sleep() function is used in Golang to pause the execution of the script for a certain period. The following script will calculate the average of three numbers and wait for 3 seconds before terminating the script.

//Add main package
package main
//Import required packages
import (
    "fmt"
    "time"
)
func main() {

    fmt.Println("Start executing the script...")
    //Define three variables
    a := 40
    b := 30
    c := 29
    //Print the variables
    fmt.Printf("Three numbers are : %d, %d, %d\n", a, b, c)
    fmt.Println("Calculating the average of three numbers...")
    avg := (a + b + c)/3
    //Delay for 3 seconds
    time.Sleep(3 * time.Second)
    //Print the results
    fmt.Printf("The average value is %d\n", avg)
    fmt.Println("Program terminated.")
}

The following output will appear after executing the script.

p19

Go to top


Golang time

The time package is used in Golang to read the current date and time. This package has many methods and properties to read the date and time in different ways. The date and time, ‘Mon Jan 2 15:04:05 -0700 MST 2006’ is used as the reference value in Golang to access the date and time. The uses of the time package have been shown in the following example.

package main
//Import required packages
import (
    "fmt"
    "time"
)

func main() {
  //Read the current date and time
  today := time.Now()
  //Print the current date
  fmt.Printf("Today is %s.\n", today.Format("02-Jan-2006"))
  //Print the current date and time
  fmt.Printf("The current date and time is %s\n.", today.Format(time.RFC1123))
}

The following output will appear after executing the script.

Go to top


Golang uuid

The UUID or Universally Unique Identifier can be generated by Golang script. It is a 128-bit unique value to identify the computer system. You have to download the uuid from the github.com/google/uuid before executing the following script.

Go to the home directory and run the following commands to download the required package to generate the uuid by Golang script.

$ go mod init uuid
$ go get github.com/google/uuid

In the following script, the first uuid is generated by using the uuid.New() function that returns a unique identifier. The second uuid is generated by the uuid.NewUUID() function that returns two values. The value contains the unique identifier and the second value contains the error message if it exists.

package main
//Import required packages
import (
    "fmt"
    "github.com/google/uuid"
)
func main() {

    //Generate a unique ID using New() function
    newID := uuid.New()
    fmt.Printf("Generated first UUID is %s.\n", newID)

    //Generate a unique ID using NewUUID() function
    newID, err := uuid.NewUUID()
    //Check for error
    if err == nil {
        fmt.Printf("Generated second UUID is %s.\n", newID)
    }else{
        fmt.Println(err)
    }
}

The following output will appear after executing the script.

p21

Go to top


Golang read file

The io/ioutil package of Golang is used to read the content of a file. The ReadFile() function of this package reads the whole content of a file. This function returns the full content of the file into a variable if the file exists otherwise an error message will be returned. The way of reading the full content of an existing text file has been shown in the following script.

//Add main package
package main
//Import required packages
import (
    "io/ioutil"
    "fmt"
    "log"
)

func main() {

    //Read a text file
    text, err := ioutil.ReadFile("Languages.txt")
    //Check for error
    if err == nil {
        fmt.Printf("Content of the file:\n\n")
        fmt.Println(string(text))
    }else{
        log.Fatalf("File read error: %v", err)
    }

}

The following output will appear after executing the script.

p22

Go to top


Golang read file line by line

The “bufio” package of Golang is used to read the content of a file line by line. In the following script, the bufio.NewScanner() has been used to create an object to read the file. Next, the Scan() function has been used with the loop to read and print each line of the file.

//Add main package
package main
//Import required packages
import (
    "fmt"
    "os"
    "bufio"
)
func main() {

    //Open a text file for reading
    fh, err  := os.Open("Languages.txt")
    //Check for error
    if err == nil {
        //Scan the file content
        read := bufio.NewScanner(fh)
        //Read the file line by line
        for read.Scan() {
            fmt.Println(read.Text())
        }
    }else{
        fmt.Println(err)
    }
    //Close the file
    defer fh.Close()
}

The following output will appear after executing the script.

p23

Go to top


Golang write to file

The os package of the Golang is used to open a file for writing and the WriteString() function is used to write content into a file. The way of creating and writing a text file of three lines is by using the os package.

package main
//Import required packages
import (
    "fmt"
    "os"
)

func main() {

    //Open a file for writing
    fh, err1 := os.Create("items.txt")
    //Check for file creation error
    if err1 == nil {
         //Write into the file
         _, err2 := fh.WriteString("Pen\nPencil\nRuler\n")
         //Check for file writing error
         if err2 != nil {
              fmt.Println("File write error occurred.\n")
         }
    }else{
         fmt.Println("File creation error occurred.\n")
    }
    //Close the file
    defer fh.Close()
}

The following output will appear after executing the script. The output shows that the items.txt file has been created successfully.

p24

Go to top

 

Golang checks if file exists

The os package of the Golang can be used to check the existence of the file. In the following script, the file path will be taken from the script. If the path does not exist then the os.State() function will return an os.ErrNotExist error.

package main
//Import required module
import (
        "errors"
        "fmt"
        "os"
)

func main() {
     var filepath string
     fmt.Printf("Enter an existing filename: ")
     //Take the file path from the user
     fmt.Scan(&filepath)
     //Check the file path
     _, error := os.Stat(filepath)

      //Check the output of the os.Stat
      if !errors.Is(error, os.ErrNotExist) {
           fmt.Println("File is found.")
      } else {
           fmt.Println("File is not found.")
      }
}

The following output will appear after executing the script.

p25

Go to top


Golang csv

The “encoding/csv” package is used in Golang to read the content of the CSV file. The csv.NewReader() function is used to read the CSV file. Create a CSV file before executing the script of this example. Here, the customers.csv file has been used to show the way of reading the CSV file.

package main
//Import required packages
import (
   "encoding/csv"
   "fmt"
   "os"
)

func main() {
    //Open a CSV file for reading
    fh, err := os.Open("customers.csv")
    //Check for the error
    if err != nil {
        fmt.Println(err)
    }else{
         //Create an object to read the CSV file
         scanner := csv.NewReader(fh)
         //Read all records of the CSV file
         records, _ := scanner.ReadAll()
         //Read the CSV file line by line
         for _, r := range records {
             for _, c := range r {
                 fmt.Printf("%s,", c)
             }
             fmt.Println()
        }
}
 //Close the file
 defer fh.Close()
}

The following output will appear after executing the script.

p26

Go to top


Golang yaml

The yaml.Marshal() function is used in Golang to read the content of the yaml data. You have to download the yaml package to use the yaml.Marshal(). Go to the home directory and run the following command to download the yaml package.

$ go get <a href="http://gopkg.in/yaml.v2">gopkg.in/yaml.v2</a>

In the following script, a structure variable of four elements has been declared that has been used later to define a yaml object with data. Next, the yaml.Marshal() function has been used to access the yaml data.

package main
//Import required packages
import (
    "fmt"
    "gopkg.in/yaml.v2"
)

//Declare a structure of 4 elements
type Book struct {
    Title string
    Author string
    Publication string
    Price string
}

func main() {

    //Create an object of the structure
    book1 := Book{
        Title: "Learning Go",
        Author: "John Bodner",
        Publication: "O'Relly",
        Price: "$39",
    }

    //Read the yaml data based on the struct
    y_data, err := yaml.Marshal(&book1)

    //Checkk for the error
    if err == nil {
        //Print the yaml data
        fmt.Println(string(y_data))
    }else{
        fmt.Printf("Error while Marshaling. %v", err)
    }
}

The following output will appear after executing the script.

p27

Go to top


Golang http request

The net/http package of the Golang is used to send the http requests to a website. The http.Get() function is used to send the request. It returns the response from the site or the error message. The way of sending the http request to the website, https://example.com has been shown in the following script.

package main
//Import required packages
import (
   "fmt"
   "net/http"
)

func main() {
   //Send a GET request to a website
   res, err := http.Get("https://example.com")
   //Check for error
   if err == nil {
      //Print the response sent by the website
      fmt.Println(res)
   }else{
      //Print the error message
      fmt.Println(err)
   }
}

The following output will appear after executing the script.

p28

Go to top


Golang command line arguments

The values that are passed at the time of the execution of the script are called command-line argument values. The os package is used to read the command line argument values in Golang. The argument values are stored in the Args[] array. The for loop with the range has been used in the script to print the argument values without the script name in each line.

package main
//Imports required packages
import (
    "fmt"
    "os"
)

func main() {

    fmt.Println("All argument values are:")
    //Print all argument values with the script name
    fmt.Println(os.Args)

    fmt.Println("Argument values:")
    //Print all argument values without a script name
    for in, _ := range os.Args {
        if in == 0 {
            continue
        }
        fmt.Println(os.Args[in])
    }
}

The following output will appear after executing the script.

p29

Go to top


Golang error handling

Golang has no try-catch block like other programming languages. However, the errors package can be used in Golang to handle errors in the script. In the following script, an integer number will be taken from the user. If the user takes a negative number then an error message will be printed. The errors.New() function has been used here to generate the error message.

package main
//Import required packages
import (
  "errors"
  "fmt"
)

func main() {

  var n int
  fmt.Printf("Enter a number: ")
  fmt.Scan(&n)

  //Check the input value
  result, err := Positive(n)

  //Check for error
  if err != nil {
    fmt.Println(err)
  } else {
    fmt.Printf("%d %s\n", n, result)
  }
}

///Define function to check positive number
func Positive(num int) (string, error) {
  if num < 0 {
    return "", errors.New("Type a positive number.")
  }else{
      return "number is positive.", nil
  }
}

The following output will appear after executing the script.

p30

Go to top

Conclusion:

Golang is a popular programming language now that has many useful packages like the Python programming language. Any novice user can learn Golang as a first programming language because it is very easy to learn. The basic 30 Golang examples have been explained in this tutorial to learn Golang from the beginning and the learners will be able to write programs in Golang. One of the major limitations of this language is that it does not contain the features of object-oriented programming but it is good for learning structured programming.

Share Button

Source: linuxhint.com

Leave a Reply