Skip to content

Instantly share code, notes, and snippets.

@adithyamaheshb
Created April 23, 2020 04:09
Show Gist options
  • Save adithyamaheshb/2e40753d5c0c9b18e29a5c3ce0e9f978 to your computer and use it in GitHub Desktop.
Save adithyamaheshb/2e40753d5c0c9b18e29a5c3ce0e9f978 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strconv"
)
// Always make sure to use the variables you have declared
// otherwise the build fails
// Whenevr you are declaring variables at the package level
// you cannot use the ```:=``` syntax
// you have to use the full declaration
// If the variable is at the package level and lower case, it is package scoped
// and any file in the same package can access that variable
var m int = 29
// M If the variable is at the package level and upper case
// it can be exported from the package and globally visible
var M int = 56
// Another best practice of declaring variables in Go is that
// the length of the varibale name should actually reflect the life of the variable
// Also keep the acronyms uppercase i.e, like URL and HTTPRequest
// Declaring multiple variables at once
var (
firstName string = "Adithya Mahesh"
lastName string = "Bariki"
age int = 25
)
func main() {
// Block scoped
var i int
i = 72
var j int = 72
k := 42
var l float32 = 72.96
fmt.Printf("%v, %T\n", i, i)
fmt.Printf("%v, %T\n", j, j)
fmt.Printf("%v, %T\n", k, k)
fmt.Printf("%v, %T\n", l, l)
fmt.Printf("%v, %T\n", m, m)
fmt.Println("Package level Scope(m)", m)
var m int = 92
fmt.Println("Function level Scope(m)", m)
// You should explicitly convert the types in Go,
// so that you are aware of the data loss as shown in the example
var n int
n = int(l)
fmt.Printf("%v, %T\n", n, n)
// You haveto use `strconv` package to convert variables of any type to string
// And Itoa() means Integer to ASCII
var o string
o = strconv.Itoa(n)
fmt.Printf("%v, %T\n", o, o)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment