Programming with GO Lang Shishir Dwivedi
Programming with GO LangShishir 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 for Testing▪ 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 Apppackage 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 := 6if 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 := 0for {
y++fmt.Println("Value of Y 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 + yfmt.Println("I don't return any value, i calculate and
print", z)}
Functions in Go
func functionWithReturnValue(x, y string) (z string) {z = x + yreturn //Named return value automatically returns
value of z}
func funcWithMultipleReturnValue(x, y string) (a, b, c string) {
a = xb = yc = x + yreturn a, b, c
}
Functions in Go
func doSameRandomAddition() (z int) {var arr [100]intfor 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 functionfunc 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 Gofunc main() {
fmt.Println(isFunction())x := 10y := 20a := "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() stringdoAnmialSpecificAction() string
}
type horse struct {sound stringaction string
}
type bird struct {sound stringaction string
}
type fish struct {sound stringaction 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())fmt.Println(f.makeSound())fmt.Println(f.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 := paramfmt.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]int64for x := 0; x < 100; x++ {
rand.Seed(time.Now().UnixNano())number := rand.Int63()fmt.Println("Random number generated", number)arr[x] = numbertime.Sleep(10 * time.Nanosecond)
}return arr
}
Array Slice and Map
//Slices
func sliceExample() {lenOfString := 10mySlice := 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
valuefor x := 0; x < 100; x++ {
rand.Seed(time.Now().UnixNano())number := rand.Intn(x)mapList[generateRandomString(10)] =
numbertime.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