DEV Community

Back2Basics
Back2Basics

Posted on

Go Lang Part - 01

In this blog I will teach Go programming language.
Lets compare Go with other programming languages.

Go is faster than interpreted programming languages like Python, JavaScript, Ruby, PHP. When we compare with the natively compile programming languages Rust, C, C++ its compile speed most similar. But Go has the runtime that manages the memory bit faster than Java and C#. Go uses less memory than Java and C#.

Every file of Go code has a package main at the start of the file. So, that it can run as a standalone programme. There is one more import "fmt" Where we use in the main() function for standard libraries like stdout,stdin,stderr.

Simple code

package main

import "fmt"

func main(){

  fmt.Println("starting Textio server")

}
Enter fullscreen mode Exit fullscreen mode

First we write code in human readable then build the code then there will be a runtime file to execute the file.

Image description

Machines does not understand human language so while we compile the code the human readable code converted to machine code. We can execute the programme after the compile finished.

Image description

Lets say you have written a python code and shared to your friend. Your friend has installed python to run the code. But you dont have ownership of changing the code and what was changed in the code. Its like an opensource.

Image description

In go programming language we will just compile and it will give the runtime executable. So, that the end users do not have access to the main code because the runtime executable is collection of binaries. Only thing to use that executable is installing the required tools similar to Windows OS.

Image description

Go enforces strong and static typing, meaning variables can only have a single type. A string variable like "hello world" can not be changed to an int, such as the number 3. Concatination of int and string do not allowed in strongly static typed programming languages.

package main

import "fmt"

func main(){
   var username string = "hello"
   var password string = "1234"
   fmt.Println("Authorization: Basic", username+":"+password)

}

Enter fullscreen mode Exit fullscreen mode

In Java we have the automatic Garbage collector. The Java Byte Code we have should run in JVM (Java Virtual Machine) a mini virtual machine.

Image description

In Go lang we also have the automatic garbage collector. When compile go code we got one executable have some extra code added to handle the runtime. When compare to the Java we dont have extra memory overhead in Go. When compare to Rust lang Go is in the middle on managing memory overhead.

Image description

Data Types

  • Numbers: Bigger number means large number can be stored. ex: int8 is 8 Bytes
    1. int -> Signed integers. Below are for different size of integer type. a. int -> size is based on CPU architecture 32 or 64
      • int16
      • int32
      • int64
    2. uint -> unSigned integers a. uint -> size is based on CPU architecture 32 or 64
      • uint16
      • uint32 also rune alias for uint32
      • uint64
      • uintptr
    3. byte -> for byte means 8 bits same as uint8.
    4. float -> for floating point numbers.
      • float32
      • float64
    5. complex -> for complex numbers.
      • complex64
      • complex128
  • string - for strings
  • bool for boolean
package main

import "fmt"

func main() {
  var smsSendingtLimit int
  var costPerSMS float64
  var hasPermission bool
  var username string

  fmt.Printf(
      "%v %f %v %q\n",
      smsSendingtLimit,
      costPerSMS,
      hasPermission,
      username,
  )
}
Enter fullscreen mode Exit fullscreen mode

Image description

:= Operator

Inside the function the := short assignment statement can be used in place of a var declaration. The := operator infers the type of the new variable based on the value.

package main

import "fmt"

func main() {
  var congrats string
  congrats="Happy Birthday"
  fmt.Println(congrats)
}
Enter fullscreen mode Exit fullscreen mode

Image description

Similarly with := operator for empty string shorthand notation.

package main

import "fmt"

func main() {
  penniesPerText := 2
  congrats:="Happy Birthday"
  fmt.Println(congrats)
  fmt.Printf("The type of penniesPerText %T",penniesPerText)
}
Enter fullscreen mode Exit fullscreen mode

the %T is for Type checking.

Image description

Variable declaration: You used :=, which allows Go to automatically infer the type of the variable. In this case, penniesPerText will be inferred as an int, and congrats will be inferred as a string.

Static Typing: While Go uses type inference, the types are still statically determined. Once a type is inferred, you can't change it later.

We can declare multiple variables in a single line.

package main
import "fmt"
func main(){
  averageOpenRate, displayMessage := .23, "is this avg open rate"
  fmt.Println(averageOpenRate, displayMessage)

}
Enter fullscreen mode Exit fullscreen mode

Image description

Converting numbers

We can convert from int to float or float to int

temperatureInt :=88
temperatureFloat := float64(temperatureInt)
temperatureInt := int32(temperatureFloat)
Enter fullscreen mode Exit fullscreen mode

Nibble is 4 bits where as byte is 8 bits.

Constants

Constats are declared like variables but use the const keyword. Constants can't use the := short declaration syntax.

Constants can be characters, string, boolean or numeric values. They can not be more complex types like slices, maps and structs, which are types.

As the name suggests the value of constant can not be changed.

package main
import "fmt"
func main() {
  const permiumPlaneName = " Premium Plan "
  const basicPlanName = "Basic Plan"
  fmt.Println("plan:", premiumPlanName)
  fmt.Println("plan:", basicPlanName)
}
Enter fullscreen mode Exit fullscreen mode

Constant must be known at compile time. More often than not they will be declared with a static value:

const myInt = 15
Enter fullscreen mode Exit fullscreen mode

However, constants can be computed so long as the computation can happen at compile time.
For example, this is valid:

const firstName = "Lane"
const lastName = "John"
const fullName = firstName + " " + lastName
Enter fullscreen mode Exit fullscreen mode

That said, you can't declare a constant that can only be computed at run-time.

String Formatting

  • %v If unsure what type to use. Try to use %v type variant prints the Go syntax.
fmt.Println("I am %s year old ", "way too many")
// I am %s year old way too many

Enter fullscreen mode Exit fullscreen mode
  • %s - Interpolate a string
fmt.Println("I am %s year old ", "way too many")
// I am %s year old way too many

Enter fullscreen mode Exit fullscreen mode
  • %d - Interpolate an integer in Decimal form
fmt.Println("I am %d year old", 10)
// I am 10 year old
Enter fullscreen mode Exit fullscreen mode
  • %f - Interpolate a Decimal
fmt.Println("I am %f year old", 10.523)
// I am 10.523000 year old
fmt.Println("I am %.2f year old", 10.523)
// I am 10.52 year old
Enter fullscreen mode Exit fullscreen mode

When we dont want to print statement to stdout then use fmt.Sprintf("some text") assign to a varibale use the variable when needed.


const name = "Gold"
const OpenRate = 23.5
msg := fmt.Sprintf("Hai %s,your open rate is %.1f percent", name, OpenRate)
fmt.Println(msg)

Enter fullscreen mode Exit fullscreen mode

Conditionals

if statement in Go don't use parentheses around the condition:

if height > 4 {
   fmt.Println("You are tall enough!!")
}
Enter fullscreen mode Exit fullscreen mode

else if and else are supported as you would expect:

package main
import "fmt"
func main() {

  height := 4

  if height > 6 {
    fmt.Println("You are super tall!!")
  } else if height > 4 {
    fmt.Println(" You are tall enough!")
  } else {
    fmt.Println("You are not tall enough!!")
  }

}
Enter fullscreen mode Exit fullscreen mode

Here are the some comparison operators

  • == equal to
  • != not equal to
  • < less than
  • > greater than
  • <= less than or equal to
  • >= greater than or equal to

In go some weird syntax of if condition supports

if INITIAL_STATEMENT; CONDITION {
}
Enter fullscreen mode Exit fullscreen mode

Here the length varible scope within the if block.

email := "yahoocto@gmail.com"
if length := getLength(email); length < 1 {
   fmt.Println("Length is less than 1")
} else {
   fmt.Println(" Length is greater than 1")
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay