DEV Community

Sadhan Sarker
Sadhan Sarker

Posted on

Go Basic Zero To Hero

Setup Environment

  • 1. Download Go SDK
  • 2. Now Code Editor
  • 3. Hit below command to check SDK installed or not

Or,

go version
Enter fullscreen mode Exit fullscreen mode

👏 Great! Our Environment Ready. Let's begin.

🔰 Create a Frist Application

Create a workspace directory and then create workspace/hello.go file, with including below code blocks,

package main

import "fmt"

func main() {
  fmt.Println("Hello! From Go");
}
Enter fullscreen mode Exit fullscreen mode

Note: Here, the main() method is the starting point of the application, So remember it main package is only imported where we want to start your application

Now Run your first go code. using below commands, open terminal then

go hello.go
Enter fullscreen mode Exit fullscreen mode

✅ Successfully we can run your go application. Let's go deeper.

🔰 Let's learn Go Basic types

  • Strings
  • Numbers
  • Arrays [Arrays have a fixed size.]
  • Slices [Slices have a dynamic size, unlike arrays.]
  • Type conversions
  • Pointers

Play with Go Different Types:-

package main

import "fmt"

func main() {
  // Variable declaration
  var msg1 string
  msg1 = "Hello"

  // Short form of above
  msg2 := "Hello"

  // multiline text
  message_str := `Multiline
  text`

  // Define Constants
  const PI = 1.618

  // Number
  int_num := 34            // int
  float_num := 34.0        // float64
  byte_num := byte('a')    // byte or uint8

  // Other types
  var u unsigned_int = 3   // uint (unsigned)
  var p float32 = 34.0     // 32-bit float

  // array = arrays are fixed in size
  var numbers [5]int
  int_numbers := [...]int{0, 0, 0, 0, 0}

  // slice are dynamic array = size are dynamic
  slice1 := []int{2, 3, 4}
  slice2 := []string{'ABC', 'BCD', 'DEF'}
  slice2 := []byte("Hello")

  // type conversions
  int_type := 2
  float_type := float64(int_type)
  unsigned_int_type := uint(int_type)
}
Enter fullscreen mode Exit fullscreen mode

Let's do a little bit deeper, explore pointers and functions

package main

import "fmt"

func main() {
  b := *getPointerRefFunc(2)
  fmt.Println("Value is", b)

  v1, v2 := sampleFunc(4,3)
  fmt.Println("Values are: ", v1, v2)
}

func getPointerRefFunc(arg int) (return_type *int) {
  a := arg + 3
  return &a
}

func sampleFunc(arg1, arg2 int) (int, string) { 
  return arg1 , "Hello";
}
Enter fullscreen mode Exit fullscreen mode

😰Uhoo! We are doing much. Okay, let's look up something Interesting.
Guys. The pointer is a most important concept in GO, So it's enough fo that time being.

🔰 Flow control or Conditional Statment

// if & else statements
if fruit == "apple" || fruit == "orange" {
  //.. do something
} else if fruit == "mango" && fruit == "cherry" {
  //... do something
} else {
  //...happens when none of them are matches
}


// switch statements

switch day {
  case "apple":
    //.. do something

  case "mango":
    //.. do something

  default:
    //...happens when none of them are matches
}

Enter fullscreen mode Exit fullscreen mode

🔰 Loop & Looping In Go

  // just looping
  for count := 0; count <= 10; count++ {
     fmt.Println("My counter is at", count)
  }

  // looping over array
  items := []string{"abc","def","ghi"}
  for i, val := range items {
    fmt.Printf("At position %d, the character %s is present\n", i, val)
  }

Enter fullscreen mode Exit fullscreen mode

🔰 Let's talking about Functions

  • Lambdas
  • Multiple return types
  • Named return values

func main() {

   // lambdas
   myfunc := func() bool {
     return "Hello! From Lambdas"
   }

   a, b := getMessage()
   a, b := getValue(2, 3)
}

//Multiple return types
func getMessage() (a string, b string) {
  return "Hello", "World"
}

// Named return values
func getValue(p int) (a, b int) {
  a = p + 2
  b = p - a
  return a, b
}

Enter fullscreen mode Exit fullscreen mode

🔰 Packages In Go

The packaging concept is quite smart in go language and it's pretty similar to python. It's just an awesome and important concept in Go.


// import single 
import "fmt"
import "math/rand"

// multiple imports in a single block
import (
  "fmt"        // gives fmt.Println
  "math/rand"  // gives rand.Intn
)

// we can create custom aliases like below
import custom_name "math/rand"

func main() {
  fmt.Println("My favorite number is", custom_name.Intn(10))
}

// Exporting so that we can import that from another package, 
func Hello () {
  fmt.Println("I'm From Hello Function!")
}
Enter fullscreen mode Exit fullscreen mode

Note: The package name should be the small case and with an underscore no space. Exported names begin with capital letters. Every package file has to start with the package.

🔰 Concurrency In Go

Goroutines have faster startup time than threads. Goroutines makes use of channels, a built-in way used to safely communicate between themselves.


package main
import "fmt"

func added(ch chan string, name string) {
  msg := "Hello: " + name + " | "
  ch <- msg
}

func main() {
  ch := make(chan string)   // "channel"

  // start concurrent routines
  go added(ch, "Moe")
  go added(ch, "Larry")
  go added(ch, "Curly", )

  // order isn't guaranteed)
  fmt.Println( <-ch, <-ch, <-ch )
  close(ch)   // Closing channels
}

Enter fullscreen mode Exit fullscreen mode
package main
import "fmt"

func main() {
   ch := make(chan string, 2)
   ch <- "ABC"
   ch <- "BCD"
   fmt.Println( <-ch )
   fmt.Println( <-ch )
   close(ch)      // Closing channels
}
Enter fullscreen mode Exit fullscreen mode

🔰 Structs In Go

package main

import "fmt"

type Person struct {
    name string
    address string
}

func main() {

  person := Person{"Mr. ABC", "Dhaka, Bangladesh"}

  fmt.Println(person)
  person.name = "Sadhan"

  fmt.Println(person.name)
   fmt.Println(person)
}
Enter fullscreen mode Exit fullscreen mode
package main
import "fmt"

type Employee struct {
    firstName, lastName string
    salary int
    healthy bool
}
func main() {
  employee := Employee {
     firstName: "ABC",
     lastName: "Sarker",
     salary: 1200,
     healthy: true,
 }
 fmt.Println(employee)
 fmt.Println(employee.firstName)
}
Enter fullscreen mode Exit fullscreen mode

🔰 Interface in Go

package main

import "fmt"

type I interface {
    Greeting()
}

type Human struct{}

func (Human) Greeting() {
    fmt.Println("Hello, from Golang") 
}

func f1(i I) { 
    i.Greeting()
}

func main() {
    h1 := Human{}
    f1(h1)

    var h2 Human
    f1(h2)
}
Enter fullscreen mode Exit fullscreen mode

🔰 Why Go?

  • No classes, divided into packages. Go has only structs & interface
  • No Exceptions, No generics, No annotations, No constructors
  • No support for inheritance.
  • We can do Functional programming.
  • No superclass to look out for.

👌 Congratulations!. & Thank You!
Feel free to comments, If you have any issues & queries.

🔰 Learn more from here,

Top comments (0)