KEMBAR78
ProgrammingwithGOLang | PPTX
Programming with GO Lang
Shishir Dwivedi
Why Go Lang?
▪ Multicore Performance
▪ Microservices: Go use asynchronous I/O so that our application can interact
with any number of services without blocking web requests.
▪ Concurrency
▪ Static Binaries:Go applications compile quickly and launch immediately.
▪ Testing: Go Provide inbuilt support forTesting
▪ Benchmarking: Go Provide in build support for benchmarking
▪
Content
▪ First Go App.
▪ Types in Go
▪ Loops in Go
▪ Functions and function pointers
▪ Array , Slice and Map
▪ Interface
▪ Error Handling.
Basic Go App
package main
import "fmt"
func main() {
fmt.Println("Hello, shishir")
}
Types in Go
func learnTypes() {
str := "Learn Go !"
str1 := `A "raw" string literal
can include line breaks.`
fmt.Println("Print String:", str, "Print Multi line string:", str1)
f := 3.14554646457 //This is float value.
complex := 3 + 4i //This is complex number.
fmt.Println("print float value", f, "Print complex number", complex)
Types in Go
var arr [4]int //delcaration of array. At run time default value of int will be
given //which is 0
arr1 := [...]int{2, 4, 6, 78, 9, 90, 0}
fmt.Println("arr with default value", arr, "array with init value", arr1)
}
Loops in Go
func learnLoops() {
x := 6
if x > 5 {
fmt.Println("value of x is greater that 5")
}
fmt.Println("Lets print table of 2")
for i := 0; i <= 10; i++ {
fmt.Println(i * 2)
}
Loops in Go
//While loop.
y := 0
for {
y++
fmt.Println("Value ofY is :", y)
if y > 100 {
fmt.Println("Y value reached to 100")
break
}
}
Functions in Go
package main
import "fmt"
import "math/rand"
import "time"
func isFunction() (x string) {
return "Yes i am a function"
}
func parameterizedFunction(x, y int) {
z := x + y
fmt.Println("I don't return any value, i calculate and print", z)
}
Functions in Go
func functionWithReturnValue(x, y string) (z string) {
z = x + y
return //Named return value automatically returns value of z
}
func funcWithMultipleReturnValue(x, y string) (a, b, c string) {
a = x
b = y
c = x + y
return a, b, c
}
Functions in Go
func doSameRandomAddition() (z int) {
var arr [100]int
for x := 0; x < 100; x++ {
rand.Seed(time.Now().UnixNano())
y := rand.Intn(1000000)
fmt.Println("Random number generated is", y)
arr[x] = y
}
for x := 0; x < 100; x++ {
z = z + arr[x]
}
return z
}
Functions in Go
//Function having return type as function
func myfunc(x string) func(y, z string) string {
return func(y, z string) string {
return fmt.Sprintf("%s %s %s", y, z, x)
}
}
Functions in Go
// Deferred statements are executed just before the function returns.
func learnDefer() (ok bool) {
defer fmt.Println("deferred statements execute in reverse (LIFO)
order.")
defer fmt.Println("nThis line is being printed first because")
// Defer is commonly used to close a file, so the function closing
the
// file stays close to the function opening the file.
return true
}
Functions in Go
func main() {
fmt.Println(isFunction())
x := 10
y := 20
a := "Hello My Name is"
b := "Shishir"
parameterizedFunction(x, y)
z := functionWithReturnValue(a, b)
fmt.Println(z)
a, b, c := funcWithMultipleReturnValue(a, b)
fmt.Println("value of 1st Return", a, "value of 2nd return", b,
"Value of 3rd return", c)
functionOverloading(x, a)
f := doSameRandomAddition()
fmt.Println("Sum of array is :", f)
fmt.Println(myfunc("shishir")("Hello", "My name is"))
learnDefer()
}
Method Receiver and Interface
package main
import (
"fmt"
)
//While technically Go isn’t an Object Oriented Programming
language,
// types and methods allow for an object-oriented style of
programming.
//The big difference is that Go does not support type inheritance
but instead has
//a concept of interface.
type user struct {
name, lastname string
}
Method Receiver and Interface
func (u user) greetMe() {
fmt.Println("My name is :", u.name, u.lastname)
}
type Person struct {
name user
}
func (a Person) greetMe() {
fmt.Println(a.name.name, a.name.lastname)
}
Method Receiver and Interface
func main() {
u := user{"shishir", "dwivedi"}
x := user{name: "shishir"}
y := user{lastname: "dwivedi"}
z := user{}
u.greetMe()
x.greetMe()
y.greetMe()
z.greetMe()
}
Method Receiver and Interface
type animal interface {
makeSound() string
doAnmialSpecificAction() string
}
type horse struct {
sound string
action string
}
type bird struct {
sound string
action string
}
type fish struct {
sound string
action string
}
Method Receiver and Interface
//Implemnting interfaces
func (h horse) makeSound() string {
return h.sound
}
func (h horse) doAnmialSpecificAction() string {
return h.action
}
func (b bird) makeSound() string {
return b.sound
}
func (b bird) doAnmialSpecificAction() string {
return b.action
Method Receiver and Interface
func (f fish) doAnmialSpecificAction() string {
return f.action
}
func (f fish) makeSound() string {
return f.sound
}
h := horse{"Horse Running", "Running"}
b := bird{"Bird Sound", "flying"}
f := fish{"fishSound", "swimining"}
fmt.Println(h.makeSound())
fmt.Println(h.doAnmialSpecificAction())
fmt.Println(b.makeSound())
fmt.Println(b.doAnmialSpecificAction())
Method Receiver and Interface
func main(){
h := horse{"Horse Running", "Running"}
b := bird{"Bird Sound", "flying"}
f := fish{"fishSound", "swimining"}
fmt.Println(h.makeSound())
fmt.Println(h.doAnmialSpecificAction())
fmt.Println(b.makeSound())
fmt.Println(b.doAnmialSpecificAction())
fmt.Println(f.makeSound())
fmt.Println(f.doAnmialSpecificAction())
}
Empty Interface
// Empty interface is used to pass any variable number of paramter.
func variableParam(variableInterface ...interface{}) {
// underscore (_) is ignoring index value of the array.
for _, param := range variableInterface {
paramRecived := param
fmt.Print(paramRecived)
}
}
func main() {
variableParam("shishir", 2, 3+4i, "hello", 3.445665, h, b, f)
}
Pointer Receiver
//Pointer Reciver.: you can pass address of the reciver to func if you want to
manipulate
// Actual reciever. If address in not passed one copy is created and manipulation is
//Done at that copy.
func (h *horse) pointerReciver() {
h.sound = "I am chaning horse sound"
h.action = "i am chaning horse action"
}
func (h *horse) doSomethingElse() {
h.sound = "hhhh"
h.action = "action"
}
Pointer Receiver
func main() {
horse := &horse{"Horse", "Run"}
horse.pointerReciver()
}
Array Slice and Map
package main
import (
"fmt"
"math/rand"
"time"
)
//Function whose return type is array.
//Function should return with type and memory size as well.
func arrayFunction() (arr1 [100]int64) {
var arr [100]int64
for x := 0; x < 100; x++ {
rand.Seed(time.Now().UnixNano())
number := rand.Int63()
fmt.Println("Random number generated", number)
arr[x] = number
time.Sleep(10 * time.Nanosecond)
}
return arr
}
Array Slice and Map
//Slices
func sliceExample() {
lenOfString := 10
mySlice := make([]string, 0)
mySlice = append(mySlice, "shishir")
fmt.Println(mySlice, "Lenght of slice", len(mySlice))
mySlice = append(mySlice, "Dwivedi")
for x := 0; x < 100; x++ {
mySlice = append(mySlice, generateRandomString(lenOfString))
}
fmt.Print(mySlice)
x := mySlice[:10]
fmt.Println(x)
x = mySlice[:]
fmt.Println(x)
x = mySlice[20:]
fmt.Println(x)
}
Array Slice and Map
func generateRandomString(strlen int) string {
arr := make([]byte, strlen)
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
for x := 0; x < strlen; x++ {
rand.Seed(time.Now().UnixNano())
arr[x] = chars[rand.Intn(len(chars))]
time.Sleep(10 * time.Nanosecond)
}
return string(arr)
}
Array Slice and Map
func mapExample() {
mapList := make(map[string]int)
//adding random string as key and random int as value
for x := 0; x < 100; x++ {
rand.Seed(time.Now().UnixNano())
number := rand.Intn(x)
mapList[generateRandomString(10)] = number
time.Sleep(10 * time.Nanosecond)
}
//Printing Map using Range Iterator.
fmt.Println(mapList)
}
Array Slice and Map
func main() {
fmt.Println("Array following number:", arrayFunction())
multiDimenisonalArray()
sliceExample()
mapExample()
}
Error Handling
func fileIOWithFlags() {
file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_RDWR, 0660)
if err != nil {
size, _ := file.WriteString(generateRandomString(10))
fmt.Println(size)
}else{
fmt.Errorf(string(err.Error()))
}
}
func generateRandomString(strlen int) string {
arr := make([]byte, strlen)
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
for x := 0; x < strlen; x++ {
rand.Seed(time.Now().UnixNano())
arr[x] = chars[rand.Intn(len(chars))]
}
fmt.Println("String which is generated is:", string(arr))
return string(arr)
}
Thank You

ProgrammingwithGOLang

  • 1.
    Programming with GOLang Shishir Dwivedi
  • 2.
    Why Go Lang? ▪Multicore Performance ▪ Microservices: Go use asynchronous I/O so that our application can interact with any number of services without blocking web requests. ▪ Concurrency ▪ Static Binaries:Go applications compile quickly and launch immediately. ▪ Testing: Go Provide inbuilt support forTesting ▪ Benchmarking: Go Provide in build support for benchmarking ▪
  • 3.
    Content ▪ First GoApp. ▪ Types in Go ▪ Loops in Go ▪ Functions and function pointers ▪ Array , Slice and Map ▪ Interface ▪ Error Handling.
  • 4.
    Basic Go App packagemain import "fmt" func main() { fmt.Println("Hello, shishir") }
  • 5.
    Types in Go funclearnTypes() { str := "Learn Go !" str1 := `A "raw" string literal can include line breaks.` fmt.Println("Print String:", str, "Print Multi line string:", str1) f := 3.14554646457 //This is float value. complex := 3 + 4i //This is complex number. fmt.Println("print float value", f, "Print complex number", complex)
  • 6.
    Types in Go vararr [4]int //delcaration of array. At run time default value of int will be given //which is 0 arr1 := [...]int{2, 4, 6, 78, 9, 90, 0} fmt.Println("arr with default value", arr, "array with init value", arr1) }
  • 7.
    Loops in Go funclearnLoops() { x := 6 if x > 5 { fmt.Println("value of x is greater that 5") } fmt.Println("Lets print table of 2") for i := 0; i <= 10; i++ { fmt.Println(i * 2) }
  • 8.
    Loops in Go //Whileloop. y := 0 for { y++ fmt.Println("Value ofY is :", y) if y > 100 { fmt.Println("Y value reached to 100") break } }
  • 9.
    Functions in Go packagemain import "fmt" import "math/rand" import "time" func isFunction() (x string) { return "Yes i am a function" } func parameterizedFunction(x, y int) { z := x + y fmt.Println("I don't return any value, i calculate and print", z) }
  • 10.
    Functions in Go funcfunctionWithReturnValue(x, y string) (z string) { z = x + y return //Named return value automatically returns value of z } func funcWithMultipleReturnValue(x, y string) (a, b, c string) { a = x b = y c = x + y return a, b, c }
  • 11.
    Functions in Go funcdoSameRandomAddition() (z int) { var arr [100]int for x := 0; x < 100; x++ { rand.Seed(time.Now().UnixNano()) y := rand.Intn(1000000) fmt.Println("Random number generated is", y) arr[x] = y } for x := 0; x < 100; x++ { z = z + arr[x] } return z }
  • 12.
    Functions in Go //Functionhaving return type as function func myfunc(x string) func(y, z string) string { return func(y, z string) string { return fmt.Sprintf("%s %s %s", y, z, x) } }
  • 13.
    Functions in Go //Deferred statements are executed just before the function returns. func learnDefer() (ok bool) { defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("nThis line is being printed first because") // Defer is commonly used to close a file, so the function closing the // file stays close to the function opening the file. return true }
  • 14.
    Functions in Go funcmain() { fmt.Println(isFunction()) x := 10 y := 20 a := "Hello My Name is" b := "Shishir" parameterizedFunction(x, y) z := functionWithReturnValue(a, b) fmt.Println(z) a, b, c := funcWithMultipleReturnValue(a, b) fmt.Println("value of 1st Return", a, "value of 2nd return", b, "Value of 3rd return", c) functionOverloading(x, a) f := doSameRandomAddition() fmt.Println("Sum of array is :", f) fmt.Println(myfunc("shishir")("Hello", "My name is")) learnDefer() }
  • 15.
    Method Receiver andInterface package main import ( "fmt" ) //While technically Go isn’t an Object Oriented Programming language, // types and methods allow for an object-oriented style of programming. //The big difference is that Go does not support type inheritance but instead has //a concept of interface. type user struct { name, lastname string }
  • 16.
    Method Receiver andInterface func (u user) greetMe() { fmt.Println("My name is :", u.name, u.lastname) } type Person struct { name user } func (a Person) greetMe() { fmt.Println(a.name.name, a.name.lastname) }
  • 17.
    Method Receiver andInterface func main() { u := user{"shishir", "dwivedi"} x := user{name: "shishir"} y := user{lastname: "dwivedi"} z := user{} u.greetMe() x.greetMe() y.greetMe() z.greetMe() }
  • 18.
    Method Receiver andInterface type animal interface { makeSound() string doAnmialSpecificAction() string } type horse struct { sound string action string } type bird struct { sound string action string } type fish struct { sound string action string }
  • 19.
    Method Receiver andInterface //Implemnting interfaces func (h horse) makeSound() string { return h.sound } func (h horse) doAnmialSpecificAction() string { return h.action } func (b bird) makeSound() string { return b.sound } func (b bird) doAnmialSpecificAction() string { return b.action
  • 20.
    Method Receiver andInterface func (f fish) doAnmialSpecificAction() string { return f.action } func (f fish) makeSound() string { return f.sound } h := horse{"Horse Running", "Running"} b := bird{"Bird Sound", "flying"} f := fish{"fishSound", "swimining"} fmt.Println(h.makeSound()) fmt.Println(h.doAnmialSpecificAction()) fmt.Println(b.makeSound()) fmt.Println(b.doAnmialSpecificAction())
  • 21.
    Method Receiver andInterface func main(){ h := horse{"Horse Running", "Running"} b := bird{"Bird Sound", "flying"} f := fish{"fishSound", "swimining"} fmt.Println(h.makeSound()) fmt.Println(h.doAnmialSpecificAction()) fmt.Println(b.makeSound()) fmt.Println(b.doAnmialSpecificAction()) fmt.Println(f.makeSound()) fmt.Println(f.doAnmialSpecificAction()) }
  • 22.
    Empty Interface // Emptyinterface is used to pass any variable number of paramter. func variableParam(variableInterface ...interface{}) { // underscore (_) is ignoring index value of the array. for _, param := range variableInterface { paramRecived := param fmt.Print(paramRecived) } } func main() { variableParam("shishir", 2, 3+4i, "hello", 3.445665, h, b, f) }
  • 23.
    Pointer Receiver //Pointer Reciver.:you can pass address of the reciver to func if you want to manipulate // Actual reciever. If address in not passed one copy is created and manipulation is //Done at that copy. func (h *horse) pointerReciver() { h.sound = "I am chaning horse sound" h.action = "i am chaning horse action" } func (h *horse) doSomethingElse() { h.sound = "hhhh" h.action = "action" }
  • 24.
    Pointer Receiver func main(){ horse := &horse{"Horse", "Run"} horse.pointerReciver() }
  • 25.
    Array Slice andMap package main import ( "fmt" "math/rand" "time" ) //Function whose return type is array. //Function should return with type and memory size as well. func arrayFunction() (arr1 [100]int64) { var arr [100]int64 for x := 0; x < 100; x++ { rand.Seed(time.Now().UnixNano()) number := rand.Int63() fmt.Println("Random number generated", number) arr[x] = number time.Sleep(10 * time.Nanosecond) } return arr }
  • 26.
    Array Slice andMap //Slices func sliceExample() { lenOfString := 10 mySlice := make([]string, 0) mySlice = append(mySlice, "shishir") fmt.Println(mySlice, "Lenght of slice", len(mySlice)) mySlice = append(mySlice, "Dwivedi") for x := 0; x < 100; x++ { mySlice = append(mySlice, generateRandomString(lenOfString)) } fmt.Print(mySlice) x := mySlice[:10] fmt.Println(x) x = mySlice[:] fmt.Println(x) x = mySlice[20:] fmt.Println(x) }
  • 27.
    Array Slice andMap func generateRandomString(strlen int) string { arr := make([]byte, strlen) const chars = "abcdefghijklmnopqrstuvwxyz0123456789" for x := 0; x < strlen; x++ { rand.Seed(time.Now().UnixNano()) arr[x] = chars[rand.Intn(len(chars))] time.Sleep(10 * time.Nanosecond) } return string(arr) }
  • 28.
    Array Slice andMap func mapExample() { mapList := make(map[string]int) //adding random string as key and random int as value for x := 0; x < 100; x++ { rand.Seed(time.Now().UnixNano()) number := rand.Intn(x) mapList[generateRandomString(10)] = number time.Sleep(10 * time.Nanosecond) } //Printing Map using Range Iterator. fmt.Println(mapList) }
  • 29.
    Array Slice andMap func main() { fmt.Println("Array following number:", arrayFunction()) multiDimenisonalArray() sliceExample() mapExample() }
  • 30.
    Error Handling func fileIOWithFlags(){ file, err := os.OpenFile("file.txt", os.O_CREATE|os.O_RDWR, 0660) if err != nil { size, _ := file.WriteString(generateRandomString(10)) fmt.Println(size) }else{ fmt.Errorf(string(err.Error())) } } func generateRandomString(strlen int) string { arr := make([]byte, strlen) const chars = "abcdefghijklmnopqrstuvwxyz0123456789" for x := 0; x < strlen; x++ { rand.Seed(time.Now().UnixNano()) arr[x] = chars[rand.Intn(len(chars))] } fmt.Println("String which is generated is:", string(arr)) return string(arr) }
  • 31.