SlideShare a Scribd company logo
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

More Related Content

What's hot

C++totural file
C++totural fileC++totural file
C++totural filehalaisumit
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
Mohammad Shaker
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
SeongGyu Jo
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
명신 김
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
진성 오
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
Icalia Labs
 
The Ring programming language version 1.5.4 book - Part 23 of 185
The Ring programming language version 1.5.4 book - Part 23 of 185The Ring programming language version 1.5.4 book - Part 23 of 185
The Ring programming language version 1.5.4 book - Part 23 of 185
Mahmoud Samir Fayed
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
Bryan Helmig
 
Introduction to Go for Java Programmers
Introduction to Go for Java ProgrammersIntroduction to Go for Java Programmers
Introduction to Go for Java Programmers
Kalpa Pathum Welivitigoda
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control Structure
Mohammad Shaker
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
FITC
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
Mohammad Shaker
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
Mohammad Shaker
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
Mohammad Shaker
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
Noritada Shimizu
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
John De Goes
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
Sunscrapers
 
Ray tracing with ZIO-ZLayer
Ray tracing with ZIO-ZLayerRay tracing with ZIO-ZLayer
Ray tracing with ZIO-ZLayer
Pierangelo Cecchetto
 

What's hot (20)

C++totural file
C++totural fileC++totural file
C++totural file
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
 
The Ring programming language version 1.5.4 book - Part 23 of 185
The Ring programming language version 1.5.4 book - Part 23 of 185The Ring programming language version 1.5.4 book - Part 23 of 185
The Ring programming language version 1.5.4 book - Part 23 of 185
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
Introduction to Go for Java Programmers
Introduction to Go for Java ProgrammersIntroduction to Go for Java Programmers
Introduction to Go for Java Programmers
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control Structure
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
 
Ray tracing with ZIO-ZLayer
Ray tracing with ZIO-ZLayerRay tracing with ZIO-ZLayer
Ray tracing with ZIO-ZLayer
 

Viewers also liked

MAGNOLIA Databases Grades K-5
MAGNOLIA Databases Grades K-5MAGNOLIA Databases Grades K-5
MAGNOLIA Databases Grades K-5
Janet Armour
 
MAGNOLIA Databases Janet Armour
MAGNOLIA Databases Janet ArmourMAGNOLIA Databases Janet Armour
MAGNOLIA Databases Janet Armour
Janet Armour
 
Introducción general
Introducción generalIntroducción general
Introducción general
Emagister
 
4. Level of Female Literacy and Its Differentials in
4. Level of Female Literacy and Its Differentials in4. Level of Female Literacy and Its Differentials in
4. Level of Female Literacy and Its Differentials inDr. Ravinder Jangra
 
VS-Orientation-ORIGINAL PP-2016-17
VS-Orientation-ORIGINAL PP-2016-17VS-Orientation-ORIGINAL PP-2016-17
VS-Orientation-ORIGINAL PP-2016-17Jane Fulcher
 
Plaquette de restitution 2030
Plaquette de restitution 2030Plaquette de restitution 2030
Plaquette de restitution 2030
rennesmetropole
 
Swachh Bharat Abhiyan
Swachh Bharat AbhiyanSwachh Bharat Abhiyan
Swachh Bharat Abhiyan
Keshav Agarwal
 
1kopylov v a_informatsionnoe_pravo
1kopylov v a_informatsionnoe_pravo1kopylov v a_informatsionnoe_pravo
1kopylov v a_informatsionnoe_pravo
ccjt
 

Viewers also liked (10)

MAGNOLIA Databases Grades K-5
MAGNOLIA Databases Grades K-5MAGNOLIA Databases Grades K-5
MAGNOLIA Databases Grades K-5
 
CV
CVCV
CV
 
MAGNOLIA Databases Janet Armour
MAGNOLIA Databases Janet ArmourMAGNOLIA Databases Janet Armour
MAGNOLIA Databases Janet Armour
 
Introducción general
Introducción generalIntroducción general
Introducción general
 
4. Level of Female Literacy and Its Differentials in
4. Level of Female Literacy and Its Differentials in4. Level of Female Literacy and Its Differentials in
4. Level of Female Literacy and Its Differentials in
 
VS-Orientation-ORIGINAL PP-2016-17
VS-Orientation-ORIGINAL PP-2016-17VS-Orientation-ORIGINAL PP-2016-17
VS-Orientation-ORIGINAL PP-2016-17
 
Plaquette de restitution 2030
Plaquette de restitution 2030Plaquette de restitution 2030
Plaquette de restitution 2030
 
Cultural environment ppt
Cultural environment pptCultural environment ppt
Cultural environment ppt
 
Swachh Bharat Abhiyan
Swachh Bharat AbhiyanSwachh Bharat Abhiyan
Swachh Bharat Abhiyan
 
1kopylov v a_informatsionnoe_pravo
1kopylov v a_informatsionnoe_pravo1kopylov v a_informatsionnoe_pravo
1kopylov v a_informatsionnoe_pravo
 

Similar to ProgrammingwithGOLang

Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
Tor Ivry
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
Jaehue Jang
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
Shahzaib Ajmal
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
Frank Müller
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
Geeks Anonymes
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
Wei-Ning Huang
 
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
JaeYeoul Ahn
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
Jaehue Jang
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
Pavel Tcholakov
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
Kaz Yoshikawa
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
Frank Müller
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
Alex Payne
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
yap_raiza
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 

Similar to ProgrammingwithGOLang (20)

Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 

ProgrammingwithGOLang

  • 1. Programming with GO Lang 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 Go App. ▪ Types in Go ▪ Loops in Go ▪ Functions and function pointers ▪ Array , Slice and Map ▪ Interface ▪ Error Handling.
  • 4. Basic Go App package main import "fmt" func main() { fmt.Println("Hello, shishir") }
  • 5. 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)
  • 6. 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) }
  • 7. 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) }
  • 8. 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 } }
  • 9. 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) }
  • 10. 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 }
  • 11. 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 }
  • 12. 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) } }
  • 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 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() }
  • 15. 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 }
  • 16. 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) }
  • 17. 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() }
  • 18. 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 }
  • 19. 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
  • 20. 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())
  • 21. 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()) }
  • 22. 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) }
  • 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 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 }
  • 26. 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) }
  • 27. 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) }
  • 28. 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) }
  • 29. Array Slice and Map 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) }