The Journey of #100DaysofCode (@eliehannouch)

Hello folks, happy to join the #100DaysofCode inspired by @henna.s :fist::blush:
In this amazing journey, I’ll be sharing with you my daily progress learning Golang (moving from Node JS, Python). Starting from a hello world program at day-01 till finishing the adventure at day-100 with a complete API integrated with MongoDB. :chart_with_upwards_trend: :computer:

Day 01

What is Golang? :thinking:

Golang, an open-source, compiled, and statically typed programming language designed by Google. Built to be simple, high-performing, readable, efficient, and concurrent nature. Used for server-side programming, game development, cloud-based programming, command line tools and more.

Why Golang? :white_check_mark:

  • Simple and easy to understand by design
  • Built in dependency management (package registry)
  • First class concurrency primitives
  • Type safety enforced by the compiler
  • Compiles to machine code for high speed
  • Garbage collected (Memory Safe)

Hello World in Golang :blush:

  • 1st : Open your Golang new project and run the following command
      go mod init yourModuleName or go mod init example.com/moduleName
      Example: go mod init hello
    

The above command creates a go.mod file to track your code’s dependencies. So far, the file includes only the name of your module and the Go version your code supports. But as you add dependencies, the go. mod file will list the versions your code depends on.

image

  • 2nd: Create a main.go file
package main

import "fmt"

func main() {
	fmt.Println("Hello folks, Happy to Join the 100daysofcode!")
}

Let’s quickly analyze our simple first hello world go program :smiley::sunglasses:

  • package main: tells the Go compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program

  • import “fmt”: here we are importing the fmt package, that allows us to format basic strings, values, or anything and print them or collect user input from the console or write into a file using a writer or even print customized fancy error messages.

  • Finally we are defining our main function using the func keyword, that print for us a normal String using the fmt.Println function.

And now let’s run our main.go file using the following command to see the function result on the console :tada:
go run main.go

That was everything for our Day-01 Hello world in Golang. Stay tuned in the coming days for some amazing and advanced topics, going from zero To hero in GO :computer:

9 Likes

Hello @eliehannouch,

Super glad to see you being part of the #100Days of Journey… :tada: :partying_face: and happy that I played a part in inspiring you.

We should spread some more noise around this. :mega: :mega:

I can’t wait to see your progress in these 100 days. :smiley:

Wish you all the best :four_leaf_clover:

Cheers, :performing_arts:

3 Likes

100daysofcode - Day-02

Hello folks, Here we go, new day Day-02 and some new knowledge gained in Golang. Today we will dive in the GoLang data types.

GoLang and the different data types

  • Go is a statically typed language. Which means that variable types are known at compile time

  • Go use type inference where the compiler can infer the type of a certain variable without explicitly specify it by the developers

  • Primitive data types in GoLang

    1. Signed Integer Types (int8, int16, int, int32, int64)

    2. Unsigned Integer Types (uint8, byte, uint16, uint, uint32, uint64, uintptr)

    3. Others (bool, float32, float64, complex64, complex128)

    Rune and Strings in Golang

    • What is a Rune ?
      1. Code points define characters in unicode. In the case of Go there is a new term called rune.
      2. Runes are aliases of type int32
      3. To find a char rune we can simply write the following piece of code:
           str:= 'B'
           fmt.Println(rune(str))
          // Output: 66
  • What is a String ?
    1. String is a data type that represent a slice of bytes that are UTF-8 encoded. Strings are enclosed with double quotes.
      strExample := "Hello everyone, this a string"

    2. We can get the String length by typing the following
      len([]rune(strExample)), or len(strExample)

    3. We can use the rune() function to convert string to an array of runes

    4. Moving from String to rune

            strExample := "Hello GoLang"
            fmt.Println([]rune(strExample))

            Output: [72 101 108 108 111 32 71 111 76 97 110 103]

Type Aliases

  • Type aliasing refers to the technique of providing an alternate name for an existing type, with an aim to facilitate code refactor for large codebases.
    Example:
    - type productID int
    - type productPrice float64
5 Likes

100daysofcode - Day-03

It’s Day03 :rocket::fire:
Hello folks :blush: glad to share with you a new day dealing with golang and exploring it alongside my daily work.
Today we will talk more about the package system in go, its advantages, and how to deal with them and explore some of them in an example.

What is a Package in simple terms ?

  • In simple terms a package is a container or a box that contains multiple functions to perform specific tasks.

  • When using packages, we can organize our Go code into reusable units.

  • To use name aliasing in Go packages we can simply say:
    import s "strings", and here we can use s when calling the package instead of strings

  • To solve a common problem of importing unused packages we can simply put a blank identifier before its definition
    _ “fmt”, and in this case no error will appear

How to import a package in Go ?

  • To import a package, simply we can use the import keyword as following:
    import “fmt”

  • In the above import statement we have imported the fmt package, that is used to format basic strings, values, inputs, and outputs. And now after importing it all the available functions can be used on the fly inside our go file.

  • Let’s explore the fmt package quickly and some of its basic functions

    1. Print() : prints the data to the output screen
    2. Println(): prints the data to the output screen with a new line character at the end
    3. Scanf(): get input values using the format specifier

All these functions and much more can be used on the fly after importing the fmt package

  • Let’s explore another basic package in Golang and explore some of its basic functions, before trying them in a workable example
    import “strings” , a string package that holds different types of functions to manipulate UTF-8 encoded strings. And here some of its basic functions
    1. Compare(): a function that check if 2 strings are equal
    2. Join(): a function used to create a new string by concatenating the elements of a string array
    3. ToLower(): used to convert a string to lowercase
    4. ToUpper(): used to convert a string to uppercase

Example to showcase how to deal with these packages

// tells the Go compiler that the package should compile as
// an executable program instead of a shared library
package main
 
// here we are importing multiple packages in a single import
import (
   "fmt"
   "strings"
)
 
func main() {
 
   // transforming the string content to lower case
   lower := strings.ToLower("THE COMMUNITY IS THE BEST PLACE TO GROW")
   fmt.Println(lower)
 
   checkTxt := "Hello everyone, this is a test"
 
   // checking if the checkTxt string contains a substring called everyone
   doesItContain := strings.Contains(checkTxt, "everyone")
   fmt.Println(doesItContain)
   // Output: true
 
   // making an array of strings
   arrayOfStrings := []string{"I love", "Go Lang", "and", "MongoDB"}
   fmt.Println(arrayOfStrings)
   //output: [I love Go Lang and MongoDB]
 
   // joining the array content into one string, separated by a space
   fromArrToString := strings.Join(arrayOfStrings, " ")
   fmt.Println(fromArrToString)
   // output: I love Go Lang and MongoDB
}

How to create a custom package in Golang ?

//First we need to declare the package using the following piece of code: 
package simplecalculator

// create a simple addTwoNumbers function
func addTwoNumbers(num1, num2 int) int {
	return num1 + num2
  }

  • And now we have create a custom package called simplecalculator that contains a addTwoNumbers functions that can be imported into the main go file and used as other build in packages
5 Likes

100daysofcode - Day04

Hello folks, every day is a new challenge. And today marks the 4th day in our amazing journey where we will make a quick intro about the modules system in Golang. :blush::boom:

What is a module? :thinking:

  • In Golang, a module is a collection of Go packages stored in a file tree with a go.mod file at its root. This file defines the module’s path, which is also the import path used for your project, and its dependency requirements, which are the other modules needed for a successful build.

What is the benefit of using a module in Golang? :white_check_mark:

  • The main benefit of go modules is the ability to add dependencies to our project in any directory, and not just the Go Path directory structure.

**How to initialize a new module in Go? **

  • Simply we can run the following command on the terminal
    go mod init moduleName

What does this command do? :desktop_computer:

  • It simply create a go. mod file to track the code dependencies. When running the command, the generated file only includes the name of the module and the Go version that support our code.
    module helloworld
    go 1.17
  • To add dependencies to our go module we can simply require them, after the go version as following
   module example.com/my/thing
   go 1.17

   require example.com/other/thing v1.0.2
   require example.com/new/thing/v2 v2.3.4

or
   module example.com/my/thing
   go 1.17

   require (
	   example.com/other/thing v1.0.2
	   example.com/new/thing/v2 v2.3.4
	)
5 Likes

100daysofcode - Day05

Hello friends, the 5th day is done :white_check_mark:, a new day, and some new knowledge in Golang. In today post we will review the conditionals in Golang, how they differ from other programming languages. We will also talk about loops and how to deal with them. I hope you will enjoy reading the post :tada::blush:

First, let make a quick refresher on what conditionals are all about in any programming language?

  • Conditionals are expressions that evaluate to either true or false. They are mostly used to determine Program Flow through if statements and while loops.

What is an if statement and how it works in Golang? :thinking:

  • In simple terms we can define them a decision-making statement that guide a program to take decisions based on a specific condition, where it execute on a set of code it the specified condition is met (true) or on the other if it does not met (false)

  • In Go, we don’t :x: use brackets around the condition itself

  • If statement can be used without an else :boom:

  • A statement can precede the conditionals and any declared var in the statement is available in all other branches :tada::rocket:

  • In Golang there is no ternary operator :smiling_face_with_tear::sob:, so we need to write a full if else statement to achieve the same result.

  • Example illustrating how the if statement work in GoLang

      package main
      
      import "fmt"
      
      func main() {
      
          // If condition without an else clause
          var i int = 300
          if i%6 == 0 {
              fmt.Println(i, "is divisible by 6")
          }
          // simple and without parenthesis 🥰 
          if 20%2 == 0 {
              fmt.Println("20 is even")
          } else {
              fmt.Println("20 is odd")
          }
      
          // Statement initialization with If condition
          if n := 50; n < 0 {
              fmt.Println(n, "is negative")
          } else if n < 10 {
              fmt.Println(n, "has 1 digit")
          } else {
              fmt.Println(n, "has multiple digits")
          }
      }

What is a while loop? :thought_balloon: Does it exist in Golang? And how can we replace it :brain::bulb:

  • The while loop is used to repeat a section of code an unknown number of times until a specific condition is met.
  • In Golang there is not special keyword that makes a while loop, But luckily the for statement in Golang is so flexible and allow us to make a while loop on the fly
  • Example:
    package main
    
    import (
        "fmt"
    )
    
    func main() {
        i := 0
        for i < 50 {
            fmt.Println("i =", i)
            i += 2
       
     }

Loops In Go :repeat: :repeat_one:

First of all let’s remember, what does loops are all about in programming before diving in the Go edition

  • In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. Example for loops, while, do-while

  • In Go, the only looping construct is for, so let’s explore the different ways we can deal with

  • Example:

    package main
    
    import "fmt"
    
    func main() {
    
        // The for loop that replace while in Golang
        i := -2
        for i <= 3 {
            fmt.Println(i)
            i++
        }
        //A classical for loop.
        for j := 0; j <= 10; j++ {
            fmt.Println(j)
        }
    
        // We can use the continue keyword to jump to the next iteration of the loop
        for n := 0; n <= 5; n++ {
            if n%2 == 0 {
                continue
            }
            fmt.Println(n)
        }
    
        // A for without condition will loop repeatedly until you break out of it.
        for {
            fmt.Println("loop")
            break
        }
    }
4 Likes

100daysofcode - Day06

Hey folks, it’s the 6th day / 100, let’s explore some new topics in Golang, and make this journey a funny one :tada::smiling_face_with_three_hearts:.

In today post, we will talk about some of the basic data structures in Golang, starting with arrays, and slices.

Arrays in Golang :thinking:

What is an array in Golang?

  • A data structure, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. :sunglasses::smile:
  • Golang Arrays are one-dimensional, but you can :open_mouth: compose types to build multi-dimensional data structures.
  • Arrays Example:
    package main
    
    import "fmt"
    
    func main() {
    
        var a [5]int
        fmt.Println("Initial values of a:", a) // Output: [0 0 0 0 0]
    
        // Here we are assigning the 3rd and 5th element of the array to the values -3 and 20 respectively.
        a[2] = -3
        a[4] = 20
        fmt.Println("setting data:", a)
        fmt.Println("retrieving:", a[3])
    
        // Array length
        fmt.Println("array length:", len(a))
    
        // declaring an integer array with 5 elements
        b := [5]int{1, 2, 3, 4, 5}
        fmt.Println(b)
    
        // Creating a 2D array and filling it with values
        var twoD [2][3]int
        for i := 0; i < 2; i++ {
            for j := 0; j < 3; j++ {
                twoD[i][j] = i + j
            }
        }
        fmt.Println("Two dimensional array:", twoD)  // Output: [[0 1 2] [1 2 3]]
    }

Slices in Golang

What are Slices in Golang? :thinking:

  • A slice is a flexible data structure, made up of multiple elements all the same type. It’s a segment of dynamic arrays that can grow and shrink to fit in any place. They are index-able and have length property
  • To check the capacity of a slice, we can use a built-in method called cap :rocket:
  • To check the length of a slice, we can use the built-in method len :fist:
  • We can create a new slice using the built-in method make :boom::heart_eyes:
  • We can add new elements to an existing slice using the append method :open_mouth:
  • We can copy a slice to another one, using the copy method
  • Slices Example:
    package main
    
    import (
        "fmt"
    )
    
    func main() {
        // Delcare empty slice of type int or string or any other type
        var sliceinteger []int
    
        // Create a new slice by filling it with data
        //var filledslice = []int{1, 2, 3, 4}
    
        // Checking the capacity of a slice using the built in cap
        fmt.Println("Capacity: ", cap(sliceinteger))
    
        // Checking the length of a slice using the built in function len
        fmt.Println("Length: ", len(sliceinteger))
    
        // Create a new slice using the make keyword, with a length of 10 and type string
        var slicestring = make([]string, 10)
    
        // Add element to  the end of a slice using the append method
        slicestring = append(slicestring, "MongoDB", "GoLang", "NodeJS", "Python")
    
        // copy a slice to another
        a := []int{1, 2, 3}
        b := make([]int, 5, 10)
        copy(b, a)
        b[3] = -4
        b[4] = 5
        fmt.Println(b) // Output: [1 2 3 -4 5]
    
        // Slicing tips
        slice := []int{1, 2, 3, 4}
        fmt.Println(slice[:])   // Output: [1 2 3 4]
        fmt.Println(slice[1:])  // Output: [2 3 4]
        fmt.Println(slice[:1])  // Output: [1]
        fmt.Println(slice[:2])  // Output: [1 2]
        fmt.Println(slice[1:4]) // Output: [2 3 4]
    }
4 Likes

100daysofcode - Day 07

Hello folks, today marks our 7th day / 100 :tada::fire:, so let’s learn some amazing new topics in Golang, moving everyday toward our goal the DAY 100. :sunglasses:

Today, we will continue our tour with a new data structure the Golang map :world_map: and then we will discover the range and learn how to deal with it in go. :fist:

Maps in Golang :world_map:

What is a Map in Golang and how we can use it? :thinking::thought_balloon:

  • ❶ A built-in associative data type, that maps keys to values

  • ❷ Used for fast lookups, deletion, and data retrieval based on keys

  • ❸ Store data in key-value pairs style

  • ❹ A map cannot have identical keys

  • ❺ Called dicts or hashes in other languages

  • ❻ Maps are unordered, So each time we iterate through them , we can get a new different order of elements

  • ❼ Now let’s move to an example, where we will illustrate how we can create maps in different ways, initialize them with data, change these data, delete them and much more…

  • Golang Maps Example

    package main
    
    import (
        "fmt"
    )
    
    func main() {
    
        // First we are declaring a map with string keys and string values.
        var programmingLanguages map[string]string
    
        // Now we are initializing the map using the make function
        programmingLanguages = make(map[string]string)
    
        // Adding Data to the map
        programmingLanguages["p1"] = "GoLang"
        programmingLanguages["p2"] = "JavaScript"
        programmingLanguages["p3"] = "Python"
        programmingLanguages["p4"] = "Rust"
    
        fmt.Println(programmingLanguages) // Output: map[p1:GoLang p2:JavaScript p3:Python p4:Rust]
    
        // Access a certain value from the map
        var c1Value = programmingLanguages["p2"]
        fmt.Println(c1Value) // Output: JavaScript
    
        // Delete a value (Rust) from the map
        delete(programmingLanguages, "p4") // Output: map[p1:GoLang p2:JavaScript p3:Python]
    
        // Iterate over the map using the for loop
        for language, key := range programmingLanguages {
            fmt.Println(language, key)
        }
    
        // Get the map length
        mapLength := len(programmingLanguages)
        fmt.Println(mapLength) //  Output: 3
    }

Range in Golang :rocket:

What is a range in Golang, and how it works? :bowing_man:

  • The range keyword, used with different data structures, to iterate over them.
  • It can be used in for loops to traverse and iterate over maps, slices, arrays, channels
  • Golang Range example :wave:
    package main
    
    import "fmt"
    
    func main() {
    
        numbers := []int{1, 2, 3, 4}
        sum := 0
    
        // Iterating through the array of numbers and calculating the sum
        // We are passing _ as first argument, as the index in our case does not matter
        for _, num := range numbers {
            sum += num
        }
        fmt.Println("sum:", sum)
    
        // Here we are iterating through the array and both the index and the numbers matter
        // The first argument i --> represent the index
        // The second argument num --> represent the number
        for i, num := range numbers {
            if num == 3 {
                fmt.Println("index:", i)
            }
        }
    
        // Here we are iterating through the map
        // key reperent the available keys in the map (g,m)
        // value represent the value associated with each key
        techStack := map[string]string{"g": "Golang", "m": "MongoDB"}
        for key, value := range techStack {
            fmt.Printf("%s -> %s\n", key, value)
            // Output: g -> Golang
            //         m -> MongoDB
        }
    
        // In maps , using range we can iterate only over keys
        for key := range techStack {
            fmt.Println("key:", key)
            // Output: key: g
            //         key: m
        }
    
        // In Golang we can use the range on strings over Unicode code points
        // i represent the index
        // r represent the rune
        for i, r := range "Golang" {
            fmt.Println(i, r)
            // Output; 
            /*
            i   r
            ------
            0   71
            1   111
            2   108
            3   97
            4   110
            5   103
            */
        }
    }

3 Likes

100daysofcode - Day 08

Hello, Hello folks how it’s going on, today marks our DAY :eight: / 100 . GOLANG is going very smoothly till now :smiling_face_with_three_hearts::rocket:. I hope you are enjoying my posts, and getting to learn more about this new in demand technology.

In today post, we will talk about functions, their types, and how we can use them in Golang :handshake::man_technologist::sunglasses:

What is a function ? :thinking:

  • In Computer Science , a function is a self contained module of code with an aim to accomplish a specific task :desktop_computer: :desktop_computer:. They usually work by taking data and returning a result. It helps developers write reusable pieces of code, as they can use a defined function in many places.:partying_face:

How to declare a normal function in Golang ?

  • In Golang, to declare a new function, we do that by using the func keyword.
    After that we write the function name, the list of parameters and the return type.
  • Example:
	func ourFirstFunction (parameter1, parameter2 ,parameter3 …) datatype {
		// The function logic written here …
	}
  • Code Demo
    package main
     
    import "fmt"
     
    // A function that takes 2 integers and return the result as an int
    func addition(a int, b int) int {
       return a + b
    }
     
    // If we have multiple arguments of the same type, we can pass the type
    // to the last argument among them, like a,b,c int
    func addition2(a, b, c int) int {
       return a + b + c
    }
     
    // A golang function without any return type
    func subtract(num1 int, num2 int) {
       result := 0
       result = num1 - num2
       fmt.Println(result)
    }
     
    func main() {
     
       res1 := addition(1, 2)
       fmt.Println("1+2 =", res1)
     
       res2 := addition2(1, 2, 3)
       fmt.Println("1+2+3 =", res2)
     
       subtract(5, 3)
     
    }

Multiple Return functions in Golang

  • Go has built-in support for multiple return values. This feature is used often in idiomatic Go
  • If you only want a subset of the returned values, use the blank identifier _.
  • Example
    package main
     
    import "fmt"
     
    func values() (int, int) {
       return 10, 70
    }
     
    func main() {
     
       a, b := values()
       fmt.Println(a)  // Output: 10
       fmt.Println(b)  // Output: 70
     
       // When we use the blank identifier on the first argument
       // only the second one get returned and vice versa
       _, c := values()
       fmt.Println(c) // Output: 70
    }

Variadic Functions in Golang :sunglasses:

  • Coming from its name, a variadic function is simply a one that takes a variable number of args. And each time we call the function we can pass a varying number of arguments of the same type

  • A variadic function can be simply created by adding an ellipsis “…” to the final parameter , as the example shown below

  • Example

    package main
     
    import "fmt"
     
    // A function called addition that take a variable number of arguments
    func addition(nums ...int) {
       // 1st: We are printing the numbers
       fmt.Print(nums, " ")
       // 2nd: Iterating through the numbers and adding them
       total := 0
       for _, num := range nums {
           total += num
       }
       // 3rd: printing the total
       fmt.Println(total)
    }
     
    func main() {
     
       // Calling the function with 2 args
       addition(1, 2) // Output:  [1 2] 3
       // Calling the same function with 3 args
       addition(1, 2, 3) // Output: [1 2 3] 6
     
       // And finally here we are passing an array of numbers as an argument to the function
       nums := []int{1, 2, 3, 4}
       addition(nums...) // Output: [1 2 3 4] 10
    }
3 Likes

100daysofcode - Day 09

Hello folks, another day, and some new progress in this amazing journey. Today marks our 9th day in the 100days code challenge. And in today’s post, we will continue our tour on some new concepts in Golang. Where we will talk about anonymous functions, nested functions, and closures :tada::new::fire:

What is an anonymous function in Golang ?

  • In simple terms an anonymous function is the one declared without any named identifier.
  • It behave as any other standard function, where it can accept inputs, compute them and return a result
  • An anonymous function can be assigned to a variable.

  • Example

    package main
     
    import "fmt"
     
    func main() {
     
       // anonymous function
       var helloCommunity = func() {
           fmt.Println("Hello, MongoDB community 🥰 🚀")
       }
     
       // calling the function
       helloCommunity()
     
       // anonymous function with arguments
       var multiplication = func(a, b int) int {
           return a * b
       }
       // passing arguments to the anonymous function
       fmt.Println("Multiplication result: ",multiplication(5, 4))
    }
 

What is a nested function ? And does Golang support such functions ? :thinking:

  • A nested function is a function which is defined within another function, the enclosing function.

  • A nested function is it self invisible outside of its immediately enclosing function, but can see (access) all local objects (data, functions, types, etc.) of its immediately enclosing function.

  • Golang allow us to deal with such functions, on the fly.

  • Example

    package main
     
    import (
       "fmt"
       str "strings"
    )
    // The outer function
    func hello(name string) {
     
       // The inner function using the args name of its enclosing function
       var displayName = func() {
           updatedName := str.ToUpper(name)
           fmt.Println("Hello", updatedName)
       }
       // call the inner function
       displayName()
    }
    func main() {
       // Call the parent outer function
       hello("elie")
       // Output: Hello ELIE
    }
 

A function that returns a function ??

  • Yeh, in Golang we can simply create a function that returns a function, let us understand how we can do that, in the following example.

  • Example

    package main
    import "fmt"
     
    func helloWorld() func() {
     
     return func() {
       fmt.Println("Hello World")
     }
     
    }
     
    func main() {
     
     functionInsideFunction := helloWorld()
     functionInsideFunction()
    }
 

What is a closure in Golang ??

  • A function that references variables outside its body or scope, or in other words we can define it as an inner function that has an access to the variables in the scope in which it was created.

  • Example:

    package main
     
    import (
       "fmt"
       "strings"
    )
    // The outer function that return another anonymous function
    func displayNameInLoweCase(name string) func() string {
       greeting := "Hello,"
       // The anonymous inner function that return
       // the name passed from the outer function  concatenated with a string in lower case
       return func() string {
           transformedName := strings.ToLower(name)
           return greeting + transformedName
       }
    }
    func main() {
     
       lower := displayNameInLoweCase("JOHN")
       fmt.Println(lower())
    }
 
3 Likes

100daysofcode - Day :keycap_ten:

Hello community :man_technologist::woman_technologist:, hope you are enjoying the journey and learning some amazing things in Golang. :tada::smiling_face_with_three_hearts:
A :new: day means some new progress and time :hourglass: to share what I learned to this amazing​:heart_eyes: community. So everything stays from the community to the community.
:fist:

golang

In today’s post :clipboard: we will talk about recursion, how we can create recursive functions❓ and deal with them, then we will move to discover structs and their role :man_teacher: in Golang.

What does recursion mean ? :thinking:

  • Recursion is a method of solving a computational :robot:problem where the solution :white_check_mark: depends on solutions to smaller instances of the same problem.
  • Recursion solves such problems by using functions that call :phone: themselves from within their own code.
  • Some major examples are the Tower of Hanoi, Fibonacci Series, Factorial Problem.
  • Example
    package main
     
    import "fmt"
     
    func factorial(n int) int {
       if n == 0 {
           return 1
       }
       // the factorial function calling itself, until solving the problem
       return n * factorial(n-1)
    }
     
    func fibonacci(n int) int {
       if n < 2 {
           return n
       }
       // fibonacci calling it self
       return fibonacci(n-1) + fibonacci(n-2)
    }
     
    func main() {
       fmt.Println(factorial(4)) // Output: 24
     
       fmt.Println(fibonacci(6)) // Output: 8
    }

When should I use recursion :question::question:

  • The recursion approach is used mainly when we need to solve problems that can be broken down into smaller and repetitive problems. :repeat:

  • The recursion approach win :trophy::1st_place_medal: when the problem to be solved have many possible branches and these branches are too complex to iterate through them

  • Example: Searching in a file system

And now let’s move to learn :books: a new amazing :face_with_hand_over_mouth: concept in Golang. Structs !!

  What is a struct in Golang :question::thought_balloon: And how can we create and manipulate them ??

  • A structure or struct in Golang is a user-defined :pouting_man: :raising_hand_woman: type that allows to group/combine items of possibly different types into a single type. :sunglasses:
  • We can use structs to represent any real-world :earth_asia: entity which has some set of specific properties/fields
  • Structs are mutable.
  • To access a struct field we use the dot ·
  • To create a struct in Golang we use the type keyword, followed by the struct name and finally the struct keyword that define a new structure
     type StructureName struct {
       // structure definition 
     }
  • Structs Example
    package main
     
    import (
       "fmt"
    )
     
    func main() {
     
       // A basic car struct
       type Car struct {
           carModel       string
           productionYear int
           carColor       string
       }
     
       // declaring a struct that represent a User
       type User struct {
           firstName   string
           lastName    string
           phoneNumber string
           age         int
           jobTitle    string
           // use the car struct as a user defined data type
           car         Car
       }
     
       // To define a struct instance
       var car Car
     
       // assign value to car struct
       car = Car{
           carModel:       "BMW",
           productionYear: 2019,
           carColor:       "Black",
       }
     
       // Here we are creating a new User based on the defined struct
       // and adding a predefined car to it as a nested struct
       user1 := User{"John", "Doe", "000000", 25, "Software Engineer", car}
       fmt.Println(user1)
       // Output: {John Doe 000000 25 Software Engineer {BMW 2019 Black}}
     
       // To access a certain field from user1 we use the dot
       fmt.Println(user1.firstName, "-", user1.jobTitle)
       // Output: John - Software Engineer
     
       // To access a nested struct
       fmt.Println(user1.car.carModel) // Output: BMW
     
    }
3 Likes

100daysofcode - Day 11

Hello folks, a :new: day is here, let’s wrap it up with some new content and a lot of fun :smiling_face_with_three_hearts: :white_check_mark:. To mark this amazing day as completed :sunglasses: we should dive into a new interesting topic in Golang !! :heart_eyes:

In today’s post :clipboard:, we will make a gentle intro on Golang methods, how we can deal :handshake: :slightly_smiling_face: with them and the difference between them and functions. :facepunch:t2:

What is a method in Golang ? :thinking::robot:

  • It’s simply a normal function or we can say that a method behaves like a function but with a special receiver type. :telephone_receiver::mailbox_closed:

  • The receiver in the Golang method can be a struct or a non :x: struct type.

  • We can define the same method on different struct types :flushed: , for example if we have a Rectangle ▭ and a Square :white_medium_square: struct. We can simply define an Area method on both of them.

Why methods in Golang ? :thinking:

  • Golang is not​:no_entry: a complete object oriented programming language and hence it does not :x: support the classes architecture. :man_artist:

  • Methods were created with an aim to represent the same behavior done in classes. :white_check_mark:

  • Methods allow the grouping of all functions that belong to the same struct type together. :smile:

How to define a method in Golang ? :sunglasses:

  • To define a method in Golang we use the same function style with one extra parameter which is the receiver type between the func keyword and the method name :tada::upside_down_face:

  • Syntax Example:

	func (t Type) nameofMethod (param1, param2, …) {
		// Method logic define here in the body
	}

** Methods Example** :fist:

    package main
     
    import "fmt"
    import "math"
     
    // Defining a Rectangle struct with 2 attributes height and width
    type Rectangle struct {
       height int
       width  int
    }
     
    // Defining a Circle with a radius of type float
    type Circle struct {
       radius float64
    }
     
    // Here we are defining an Area method that deal with the rectangle struct
    func (r Rectangle) Area() int {
       return r.height * r.width
    }
     
    // Defining a method that deal with the rectangle struct and compute the perimeter
    func (r Rectangle) perimeter() int {
       return 2*r.width + 2*r.height
    }
     
    // As we can see here we are defining the same method Area
    // defined above, with a different receiver which is Circle
    func (c Circle) Area() float64 {
       return math.Pi * c.radius * c.radius
    }
     
    func main() {
       rec := Rectangle{
           height: 12,
           width:  4,
       }
       fmt.Printf("The Area of the rectangle %d\n", rec.Area())
       //Output: The Area of the rectangle 48

       fmt.Printf("The Perimeter of the rectangle %d\n", rec.perimeter())
       // Output: The Perimeter of the rectangle 32

       circ := Circle{
           radius: 4.2,
       }
       fmt.Printf("The area of the circle %f", circ.Area())
       // Output: The area of the circle 55.417694
    }

  • And we reached the end of our gentle intro defining what methods are all about, and how we can deal with them. In tomorrow’s post we will dive more into methods and make some more advanced operations on them after introducing the pointers in Go. :smiling_face_with_three_hearts: :slightly_smiling_face:

  • Stay tuned for the coming post, and let’s make this journey an amazing one, where all of us can learn and take some new skills in a funny way :fist:

3 Likes

100daysofcode - Day 12

Day 12 is already here :smiling_face_with_three_hearts::tada:. Hope you are doing well and enjoying your journeys to the maximum. So guys, it’s time to continue and dive more into some interesting topics in Golang, to wrap up the day successfully. :fist::white_check_mark:

In today’s post, we will talk about pointers in Go, their role and where to use them. Moving from some theoretical definitions to an interactive funny :star_struck: example that illustrate the targeted topics in a clear way :heart_eyes::partying_face:

What is a pointer in Golang ? :round_pushpin::thinking:

  • A pointer is simply a normal 🥹 variable that stores the address of a certain object stored in the memory.

  • A pointer points to different variables with different data types like int , string , bool and more and only stores their memory address in hexadecimal :relaxed: format. :sunglasses:

  • In Golang, pointers are called special :astonished: variables.

Why do we use pointers in Go ? :face_with_monocle::thinking:

  • Pointers are used when we need to pass :ticket: a variable by reference to a function or a method. :partying_face:
  • Pointers can be used to point :pushpin: out an array, a struct, an interface … in Golang.
  • Golang pointers avoid :no_entry: unsafe :radioactive: operations like updating or manipulating a value.

Pass by reference :vs: Pass by value :thought_balloon:

  • When we pass by value, a copy of the variable gets passed to the function to be used. This copy will be updated as required, but the original will be untouched. :blush:
  • On the other hand 🫱 , while passing a variable by reference, this means that we are passing the address :card_index: of the original variable and any operation will affect the original data stored in the variable. :smiling_face_with_three_hearts:

What is a dereference operator in Golang pointer ? :star_struck:

  • ﹡operator: the * is used to declare a :new: pointer in Go, we can use it also to access the data value from the address where the pointer is pointing. :wink:

What is the address :house: operator in Golang ?

  • & operator: the & is used to get the address :card_index: of the variable

How to declare a pointer :round_pushpin: in Golang :blush:?

  • var pointerName *Type
  • pointerName: the name of the pointer name
  • Type: the variable data type to where the pointer is pointing.
  • Example of int and string pointer:
    package main
     
    import "fmt"
     
    func main() {
       // A variable of type int
       var integerNumber int
       integerNumber = 34 // A number of type int
     
       // A pointer of type string
       var stringPointer *string
      
       // A pointer of type int
       var integerPointer *int
     
       // integerPointer pointing to integerNumber
       integerPointer = &integerNumber
     
       fmt.Println("The address on which the pointer is pointing", integerPointer)
       // Output: output in hex is 0x1400001c070
     
       fmt.Println("The value of the variable to which the pointer is pointing", *integerPointer)
       // Output: The value is: 34
     
       // To change the value of the variable via the pointer we use:
     
       *integerPointer = 45
     
       fmt.Println("The new value of the variable integerNumber is: ", integerNumber)
       // Output: 45
    }
 

Create a pointer using the :new: keyword :smiling_face_with_three_hearts:

    package main
     
    import "fmt"
     
    func main() {
     
       // create a pointer using new()
       var newPointer = new(string)
     
       *newPointer = "elie hannouch"
     
       fmt.Println(newPointer)  // 0x14000010230
       fmt.Println(*newPointer) // elie hannouch
     
    }

Functions with pointers :heart_eyes:

    package main
     
    import "fmt"
     
    func updateName(name *string) {
       // Using the dereference operator we change
       // value of the name variable
       *name = "Elie Hannouch"
     
    }
     
    func main() {
       // Name with initial value
       var name string = "John Doe"
       fmt.Println("The original name is", name) // John Doe
     
       // Passing the address of the name variable to the updateName function
       updateName(&name)
       fmt.Println("The original name is now changed to", name) // Elie Hannouch
    }

  • Stay tuned for the next posts , where we will talk about pointers with structs , methods and more :star_struck:
4 Likes

100daysofcode - Day 13

Hello, Hello, The 13th day is here. Okay folks let’s keep the amazing journey going on. :smiling_face_with_three_hearts::tada:
Before marking our day as completed, let’s dive more into some new and amazing topics in Golang. :innocent::sunglasses:

In yesterday post :white_check_mark: , we talked about pointers, how to use them and their benefits in Go, we also made a gentle intro on how we can utilize the power of pointers, when dealing with functions where we explored the concept of pass by reference vs the pass by value and how each of them deal with the code in different way, resulting in different results. :face_with_hand_over_mouth:

Today we will dive :diving_mask: more with pointers to explore how we can use them with structs and methods, and how they give us some extra power :battery: , when utilizing them correctly. In this post we will move from the theoretical definitions and explanations and get into an interactive :video_game: example that shows us how we can add pointers to structs and methods. :muscle:

Pointers with structs

    package main
     
    import "fmt"
     
    func main() {
     
       // Here we are defining a user struct with some specific attributes.
       type User struct {
           firstName   string
           lastName    string
           age         int
           email       string
           phoneNumber string
       }
     
       // And now we are gonna initialize a user instance
       user1 := User{
           firstName:   "John",
           lastName:    "Doe",
           age:         30,
           email:       "john@example.com",
           phoneNumber: "555-555-5555",
       }
     
       // create a pointer with struct type
       // to save the user address
     
       var pointer1 *User
     
       // Save the person1 struct address in the defined pointer
       pointer1 = &user1
     
       // Print the pointer struct
       fmt.Println(pointer1)
       // Output: &{John Doe 30 john@example.com 555-555-5555}
     
       // change the struct attributes values via the created pointer
       pointer1.firstName = "Jonas"
       pointer1.phoneNumber = "111-111-1111"
       fmt.Println(pointer1)
       // Updated Output: &{Jonas Doe 30 john@example.com 111-111-1111}
    }

Methods and Pointers

  • So before diving into pointers with method, let’s first of all remember together what a method is all about
  • Methods in Golang ?: It’s simply :smiling_face_with_three_hearts: a normal function or we can say that a method behaves like a function but with a special receiver type :tada:

  • In yesterday’s post we explored the difference :man_technologist: between pass by value and pass by reference in normal functions. :fist: Today we will explore Value vs Pointer receiver in methods.

Value Receiver :vs: Pointer receiver

  • A value receiver, take a copy of the type and simply pass it to the method, and in this case our method holds an object equal to the original one but each of them sit in a different memory location. And now any change happening on the passed object only affects the local one. Where the original object stay untouched

  • On the other hand, A pointer receiver: take the address of the original object and pass it to the method. And now the method has a reference to the original object location and any modification will affect this original one directly

  • Example

    package main
     
    import (
       "fmt"
    )
     
    type Car struct {
       carModel string
       price    int
    }
     
    func ValueReceiver(c Car) {
       c.carModel = "BMW"
       fmt.Println("Inside ValueReceiver method: ", c.carModel)
    }
     
    func PointerReceiver(c *Car) {
       c.price = 10000
       fmt.Println("Inside PointerReceiver method: ", c.price)
    }
    func main() {
       car1 := Car{"Nissan", 8500}
       car2 := &Car{"Mercedes", 12800}
       ValueReceiver(car1)
       fmt.Println("Inside Main after calling the value receiver : ", car1.carModel)
       PointerReceiver(car2)
       fmt.Println("Inside Main after calling the pointer receiver : ", car2.price)
    }
     
    // output:
    // Inside ValueReceiver method:  BMW
    // Inside Main after calling the value receiver :  Nissan
    // Inside PointerReceiver method:  10000
    // Inside Main after calling the pointer receiver :  10000

  • And now to analyze our code, using the value receiver which takes a copy of the object, the carModel name changed only inside the function but the change is not reflected in the main function On the other hand by using the pointer receiver which takes the address of the object, when we changed the price to 10000 this price affected the car2 object found in the main function after calling the PointerReceiver method on it.

  • So now we can demonstrate that when we use a pointer receiver , any occurring change will affect the original object and when using the value receiver the changes only affect the copied object locally.

4 Likes

100daysofcode - Day 14

Hello family :smiling_face_with_three_hearts:, yeah family the best word we can say in the world :earth_asia:. Today I’m here to share with you our big mongo DB family some amazing news. :newspaper_roll::star_struck:

Okay, let me wrap this special day here, in this special place with our amazing community. In today post I’m not going to talk about some technical topics, no it’s not the target now.

In this special day, me and @darine_tleiss :heart_eyes: the sister that God gave me, we closed a chapter, and we are officially graduated as computer scientist. :desktop_computer:

My friends, I’m here today :tada: to tell you all, keep your friends by your side :innocent::heart:. They are the God grace and the life gift :gift:. 𝟯 years passed during which I learned a lot in this wonderful major. :fist: I got to know many classmates from whom I learned many lessons :books:. And today I’m telling you all, and the joy :partying_face: fills my heart​:heart::heart:. We marked the old chapter as completed :white_check_mark: and we opened a :new: one towards a better future :handshake: and a challenging adventure :palm_tree::evergreen_tree: . Together as best friends :muscle:, we will fight till the end :end: to craft a future we deserve. :smiling_face_with_three_hearts:

image

In front ➬ of you all I would like to thank my best and closest sister Darine :heart:, for everything you did for me. We defied the odds and conquered the problems 🆇. You were the one who heard my problems, accepted my good :white_check_mark: and bad :x:. Thanks for all your sacrifices :raised_hands:. And today I’m asking God to keep you by my side until infinity. ∞∞ :smiling_face_with_three_hearts:

3 Likes

100daysofcode - Day 15

Hello folks, a new day and some new progress. In today’s post we will resume the technical content to dive more in Golang and explore some new amazing concepts. :handshake::smiling_face_with_three_hearts:

In our last Golang post, we talked about pointers and their role and how we can use them with structs, functions, methods and more. :hugs:

In today’s post we will talk about interfaces, their role and how we can utilize them. Starting from some theory :zzz: information and wrapping up with an example that shows us how we can use interfaces in a real example. :astonished::heart_eyes:

What is an interface in Golang ?

  • An interface is a collection of method signatures that a Type can implement (using methods) :wink:
  • The primary job of an interface is to provide only method signatures consisting of the method name, input arguments and return types :grin:
  • If you are coming from an OOP environment, you might have used the implement keyword in many places, but when dealing with Golang there is no need to define it explicitly. :star_struck:
  • To implement an interface in Golang we need to implement all the methods in the interface. 🫣

What happens if a struct does not implement all the interface methods ? :thinking:

  • In Golang when implementing an interface we should make sure that all methods are implemented. If not, we will receive an error :boom::x: , showing us that we are missing a certain method.
  • Example
    package main
     
    import (
       "fmt"
       "math"
    )
     
    // Here we are defining the interface geometry
    // That define 2 signatures the area and perimeter in an abstract way
    type geometry interface {
       area() float64
       perim() float64
    }
     
    // Here we have a rectangle struct with 2 attributes width and height
    type rectangle struct {
       width  float64
       height float64
    }
     
    // The circle struct with the radius attribute
    type circle struct {
       radius float64
    }
     
    // With the rectangle struct we are implementing the interface
    // with all the signatures available inside of it
    func (r rectangle) area() float64 {
       return r.width * r.height
    }
    func (r rectangle) perim() float64 {
       return 2*r.width + 2*r.height
    }
     
    // Same here for the circle functions that implement the geometry interface
    func (c circle) area() float64 {
       return math.Pi * c.radius * c.radius
    }
     
    func (c circle) perim() float64 {
       return 2 * math.Pi * c.radius
    }
    // a generic measure function
    func measure(g geometry) {
       fmt.Println(g)
       fmt.Println(g.area())
       fmt.Println(g.perim())
    }
     
    func main() {
       r := rectangle{width: 3, height: 4}
       c := circle{radius: 5}
     
       measure(r)
       measure(c)
    }

Now we reached the post end. In tomorrow’s post we will dive more into mixins and then we will introduce the functions concept, to utilize more the power of this amazing technology. :zzz::smiling_face_with_three_hearts:

3 Likes

100daysofcode - Day 16

Hello friends, here we go, the 16th day is already here :bangbang:. Let’s finish it successfully by taking some new information, to extend our existing knowledge in the Golang world. :muscle::star_struck::smiling_face_with_three_hearts:

In today’s post, I’ll move a little bit out of track :railway_track: and share with you some interesting information in String functions, that help us manipulate and deal with strings easily. :boom::handshake:

So in this post we will explore :heart_eyes: the strings package :thought_balloon:, which gives us a lot of useful string-related functions to be used out of the box. :package:

  • Example
    package main
     
    import (
       "fmt"
       s "strings"
    )
     
    var p = fmt.Println
     
    func main() {
     
       p("Contains:  ", s.Contains("test", "es"))
       p("Count:     ", s.Count("test", "t"))
       p("HasPrefix: ", s.HasPrefix("test", "te"))
       p("HasSuffix: ", s.HasSuffix("test", "st"))
       p("Index:     ", s.Index("test", "e"))
       p("Join:      ", s.Join([]string{"a", "b"}, "-"))
       p("Repeat:    ", s.Repeat("a", 5))
       p("Replace:   ", s.Replace("foo", "o", "0", -1))
       p("Replace:   ", s.Replace("foo", "o", "0", 1))
       p("Split:     ", s.Split("a-b-c-d-e", "-"))
       p("ToLower:   ", s.ToLower("TEST"))
       p("ToUpper:   ", s.ToUpper("test"))
     
     
       // Output
       /*
           Contains:   true
           Count:      2
           HasPrefix:  true
           HasSuffix:  true
           Index:      1
           Join:       a-b
           Repeat:     aaaaa
           Replace:    f00
           Replace:    f0o
           Split:      [a b c d e]
           ToLower:    test
           ToUpper:    TEST
       */
    }

4 Likes

100daysofcode - Day 17

Hello folks, a new day is here, let’s wrap it successfully by learning some new techniques to format a string in Golang. :smiling_face_with_three_hearts::star_struck::boom:

In yesterday post we talked about the string functions and how we can use them to manipulate strings in Go :handshake::hugs:

In today’s post we will learn the different ways to format a string, by moving from the boring theory part, to directly moving on directly to an interactive example to learn from it. :sunglasses::fist::four_leaf_clover:

Exercise :tada:

  package main
   
  import (
     "fmt"
  )
   
  type point struct {
     x, y int
  }
   
  func main() {
   
     p := point{5, 7}
   
     fmt.Printf("struct: %v\n", p)
     // The %v print the struct values as they are in the
     // Output: struct: {5 7}
   
     fmt.Printf("struct: %+v\n", p)
     // The %+v print the struct values with the struct field names
     // Output: struct: {x:5 y:7}
   
     fmt.Printf("struct: %#v\n", p)
     // The %#v print the struct values, field names and the syntax representation
     // Output: struct: main.point{x:5, y:7}
   
     fmt.Printf("type: %T\n", p)
     // The %T print the type of the variable
     // Output: type: main.point
   
     fmt.Printf("int: %d\n", 123)
     // The %d print the value in base 10 representation
     // Output: 123
   
     fmt.Printf("bin: %b\n", 14)
     // The %b print the value in binary
     // Output: 1110
   
     fmt.Printf("char: %c\n", 33)
     // The %c print the char corresponding to the integer
     // char: !
   
     fmt.Printf("hex: %x\n", 456)
     // The %x print the value in hexadecimal
     // Output: 1c8
   
     fmt.Printf("float1: %f\n", 78.9)
     // The %f print the float number in it's basic form
     // Output: 78.900000
   
     fmt.Printf("float2: %e\n", 123400000.0)
     fmt.Printf("float3: %E\n", 123400000.0)
     // The %e and %E print the float value in different way
     // Output: 1.234000e+08 or 1.234000E+08
   
     fmt.Printf("str: %s\n", "\"string\"")
     // The %s is used to print the string
     // Output: "string"
   
     fmt.Printf("str: %q\n", "\"string\"")
     // The %q is used to double quote strings
     // Output: "\"string\""
   
     fmt.Printf("str: %x\n", "hex this")
     // The %x render the string in base 16
     // Output: 6865782074686973
   
     fmt.Printf("pointer: %p\n", &p)
     // The %p is used to print the representation of the pointer
     // Output: 0x1400012a010
   
  }

Let’s end :end: this amazing post now, :hugs: I hope you can learn some amazing stuff from it, and stay tuned for tomorrow’s post where we will explore new interesting topics. :fist::innocent:

3 Likes

100daysofcode - Day 18

Hello folks, hope you are doing well, and you are learning some amazing things in this amazing tech world. :muscle::star_struck:

In yesterday’s post, we talked about string formatting in Golang. And in today’s post we will define the regular expressions in Golang. How to use them and to do so ? :smiling_face_with_three_hearts::sunglasses::boom:

What is a regular expression ?

  • A regular expression :pushpin: (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for “find” or “find and replace” operations on strings, or for input validation. :fist::blush::innocent:

Application of regular expression ? :desktop_computer:

  • Simple parsing.

  • The production of syntax highlighting systems. :pencil2:

  • Data Validation. :white_check_mark:

  • Data Scraping (especially web scraping)

  • Data wrangling.

Example

    package main
     
    import (
       "fmt"
       "regexp"
    )
     
    func main() {
     
       match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
       fmt.Println(match)
     
       r, _ := regexp.Compile("p([a-z]+)ch")
     
       fmt.Println(r.MatchString("peach"))
     
       fmt.Println(r.FindString("peach punch"))
     
       fmt.Println("idx:", r.FindStringIndex("peach punch"))
     
       fmt.Println(r.FindStringSubmatch("peach punch"))
     
       fmt.Println(r.FindStringSubmatchIndex("peach punch"))
     
       fmt.Println(r.FindAllString("peach punch pinch", -1))
     
       fmt.Println("all:", r.FindAllStringSubmatchIndex(
           "peach punch pinch", -1))
     
       fmt.Println(r.FindAllString("peach punch pinch", 2))
     
       fmt.Println(r.Match([]byte("peach")))
     
       r = regexp.MustCompile("p([a-z]+)ch")
       fmt.Println("regexp:", r)
     
       fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
     
       /*
           true
           true
           peach
           idx: [0 5]
           [peach ea]
           [0 5 1 3]
           [peach punch pinch]
           all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
           [peach punch]
           true
           regexp: p([a-z]+)ch
           a <fruit>
           a PEACH
       */
     
    }

3 Likes

100daysofcode - Day 19

Hello folks, a new day and some new knowledge are required. First of all I hope that your journeys are going well. In yesterday post talked about regular expressions and their roles in Golang, how they are used to validate input, events to restrict it and much more. :fist::boom::heart_eyes:

In today’s post we will dive :diving_mask: into a new amazing :star_struck: topic in Golang, the text templates feature that helps developers create dynamic content and show customized output to the user based on their needs. :hugs::smiling_face_with_three_hearts:

First of all let’s explore what the Go Template package is and how we can use it to render some dynamic content based on the user and developer needs. :muscle:🥹:desktop_computer:

What is a template in Golang ? :face_with_monocle::disappointed_relieved:

  • In simple terms a template is a file that defines a specific pattern, where the developer can dynamically change the input to show different output based on the embedded rules and logic. :boom:

  • A template simply helps developers transform their static files into more dynamic and interactive ones.

ParseFiles in Go :tada::handshake:

  • Used to parse the templates to the Golang program :white_check_mark:
  • To parse templates in golang we used the built in function ParseFiles provided by the text/template package which creates a new Template and parses the template definitions from the named files. The returned template’s name will have the base name and parsed contents of the first file. There must be at least one file. If an error :boom: occurs, parsing stops :x: and the returned *Template is nil :sob:.
  • Example
    package main
     
    import (
       "log"
       "os"
       "text/template"
    )
     
    func main() {
       template, err := template.ParseFiles("template.txt")
       // Capture any error
       if err != nil {
           log.Fatalln(err)
       }
       // Print out the template to std
       template.Execute(os.Stdout, nil)
    }

Must & Execute Method in Golang :bangbang::sunglasses::face_with_hand_over_mouth:

  • template.Must: Must is a helper that wraps a call to a function returning (*Template, error :x:) and panics if the error :disappointed_relieved: is non-nil.

  • template.Execute: Execute applies a parsed template to the specified data object, and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer.

  • Example:

    package main
     
    import (
       "log"
       "os"
       "text/template"
    )
     
    // Declare a pointer for the template.
    var temp *template.Template
     
    // we use the init() function, to make sure that the template is parsed once
    func init() {
       // The Must function take the ParseFiles response and perform error checking
       // template.Must takes the response of template.ParseFiles and does error checking
       temp = template.Must(template.ParseFiles("template.txt"))
    }
    func main() {
       // Execute myName into the template and print to Stdout
       myName := "Elie Hannouch"
       err := temp.Execute(os.Stdout, myName)
       if err != nil {
           log.Fatalln(err)
       }
    }

And now let’s wrap this amazing post up, and stay tuned for tomorrow post where we will talk more about variables and loops inside the template in Golang :muscle::heart_eyes:🫡

3 Likes