Go Programming Language

Published on Slideshow
Static slideshow
Download presentation
Download Presentation
Download PDF version
Download PDF version
Embed video
Share video
Ask about this video

Scene 1 (0s)

Go Programming Language. Code-In.

Scene 2 (6s)

Go. Developed ~2007 at Google by Robert Griesemer , Rob Pike, Ken Thompson.

Scene 3 (15s)

outline. Program Structure Why Go? Keywords, Constants and Data types Composite Types Functions Methods Interfaces.

Scene 4 (24s)

Program structure. package main //creating a package main. import " fmt ” //importing ” fmt ” package. This is similar like including a header file using #include in C/C++ func main() $ go run hello.go # to compile and run $ go build hello.go # to create a binary $ go help # for more.

Scene 5 (44s)

Why Go?. Open Source Very fast compilation Ex:- Unlike C++, Go has no templates and no inline functions. This means that Go doesn't need to perform any template or function instantiation. Cross Compilation The compiler defaults to the current architecture used for development, but we can also tell it to compile to a different architecture. This is known as cross-compilation ..

Scene 6 (1m 13s)

Go infers the type from the type of the initializer (Shorthand declaration and initialization of variable) Normal variable: var a int = 10 Shorthand: a:=10 //int b:=“string” //string In Go increment and decrement operations can’t be used as expressions, only as statements . Also, only the postfix notation is allowed..

Scene 7 (1m 36s)

No implicit conversions : Keep things explicit. C/C++ GO #include < stdio.h > int main() Output: 10.000000 package main import " fmt " func main() Output: Error: cannot use i (type int) as type float32 in assignment.

Scene 8 (1m 54s)

Keywords. Go has 25 keywords . They cannot be used as variable names..

Scene 9 (2m 7s)

Lets Understand Continue, Break and fallthrough. Continue Break fallthrough func main() sum = sum + i } fmt.Println (sum) } Output : 7 func main() sum = sum + i } fmt.Println (sum) } Output : 3 func main() } Output : One Two Three.

Scene 10 (2m 31s)

Constants and datatypes. Constants: true false iota nil Data types: int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr bool byte rune string error float32 float64 complex64 complex128 Examples of variable declaration: Var a int Var b int =10 a,b int =10,20.

Scene 11 (2m 45s)

Composite Types. Composite Datatypes are created by combining the basic types in various ways. We will talk about four such types. Arrays Slices Maps Structs.

Scene 12 (2m 56s)

Arrays. An Array is a fixed length . Individual array elements are accessed with the conventional subscript notation, where subscript runs from zero to one position less than array length. The function to find the length of the array is “ len ”. We can only have one type per array Consist of contiguous memory locations (so the in-memory representation of [4]int is just four integer values laid out sequentially) Array variable is not a pointer to the first array element, array variable stands for the whole array when we assign or pass around an array in Go — we make a copy of it (not a pointer or reference to it) Size must be an integer constant Default value of the array elements are set to ZERO var arr [3]int //array of 3 integers fmt.Println ( arr [0]) //prints the first element of an array In an array literal, if an ellipsis ‘‘...’’ appears in place of the lengt h, the array length is determined by the number of initializers. The definition of q can be simplified to q := [...]int fmt.Println (q) // [1,2,3].

Scene 13 (3m 43s)

Array - Example. package main import " fmt " func main() fmt.Println (primes) } Output: Hello World [Hello World] [2 3 5 7 11 13].

Scene 14 (4m 5s)

Slice. A Slice is a segment of an array. Slices build on arrays and provide more power, flexibility, and convenience compared to arrays. Just like arrays, Slices are indexable and have a length. But unlike arrays, they can be resized. Slice is not always a segment of an array. Example:- func main() // Short hand declaration t := []int fmt.Println ("s = ", s) fmt.Println ("t = ", t) } Output: s= [3,5,7,9,11,13,17] t=[2,4,8,16,32,64].

Scene 15 (4m 39s)

Slice implicitly has a pointer to an array Slice capacity (maximum length it can store) To create a slice from an array a, we specify two indices low ( lower bound ) and high ( upper bound ) separated by a colon. Example:- func main() // Creating a slice from the array var s []string = a[1:4] fmt.Println ("Array a = ", a) fmt.Println ("Slice s = ", s) } Output: Array a = [Alpha Beta Gamma Delta Epsilon] Slice s = [Beta Gamma Delta].

Scene 16 (5m 1s)

Array vs slice. When to use which? Arrays are useful when planning the detailed layout of memory and sometimes can help avoid allocation, but primarily they are a building block for slices. Most array programming in Go is done with slices rather than simple arrays Slices hold references to an underlying array (=it doesn’t store any data) , and if you assign one slice to another, both refer to the same array Changing the elements of a slice modifies the corresponding elements of its underlying array The length of a slice may be changed as long as it still fits within the limits of the underlying array the capacity of a slice, accessible by the built-in function cap, reports the maximum length the slice may assume. If the data exceeds the capacity, the slice is reallocated. Built-in append will do it for us;.

Scene 17 (5m 36s)

maps. A map is an unordered collection of key-value pairs. It maps keys to values. The keys are unique within a map while the values may not be. The map data structure is used for fast lookups, retrieval, and deletion of data based on keys. Declaring a map A map is declared using the following syntax - var m map[ KeyType ] ValueType For example, Here is how you can declare a map of string keys to int values - var m map[string]int.

Scene 18 (5m 58s)

The zero value of a map is nil . A nil map has no keys. Moreover, any attempt to add keys to a nilmap will result in a runtime error. Example:- package main import " fmt " func main() // Attempting to add keys to a nil map will result in a runtime error // m["one hundred"] = 100 } Output: map[] m is nil.

Scene 19 (6m 18s)

Initializing a map using the built-in make() function You can initialize a map using the built-in make() function. You just need to pass the type of the map to the make() function as in the example below. The function will return an initialized and ready to use map. Example:- func main() else // make() function returns an initialized and ready to use map. // Since it is initialized, you can add new keys to it. m["one hundred"] = 100 fmt.Println (m) } Output : map[] m is not nil map[one hundred:100].

Scene 20 (6m 48s)

Initializing a map using a map literal A map literal is a very convenient way to initialize a map with some data. You just need to pass the key-value pairs separated by colon inside curly braces Example:- package main import " fmt " func main() fmt.Println (m) } Output: map[one:1 two:2 three:3 four:4 five:5].

Scene 21 (7m 11s)

Retrieving the value associated with a given key in a map You can retrieve the value assigned to a key in a map using the syntax m[key] . If the key exists in the map, you’ll get the assigned value. Otherwise, you’ll get the zero value of the map’s value type. Example:- package main import " fmt " func main() var mobileNo = personMobileNo ["Steve"] fmt.Println ("Steve's Mobile No : ", mobileNo ) // If a key doesn't exist in the map, we get the zero value of the value type mobileNo = personMobileNo ["Jack"] fmt.Println ("Jack's Mobile No : ", mobileNo ) } Output: Steve's Mobile No : +1-8579822345 Jack's Mobile No :.

Scene 22 (7m 44s)

structs. A struct is a user-defined type that contains a collection of named fields/properties. It is used to group related data together to form a single unit . Any real-world entity that has a set of properties can be represented using a struct. Defining a struct type You can define a new struct type like this - type Person struct The type keyword introduces a new type. It is followed by the name of the type (Person) and the key. word struct to indicate that we’re defining a struct. Declaring a variable of a struct type Just like other data types, you can declare a variable of a struct type like this - // Declares a variable of type 'Person’ var p Person // All the struct fields are initialized with their zero value The above code creates a variable of type Person that is by default set to zero. For a struct, zero means all the fields are set to their corresponding zero value. Initializing a struct You can initialize a variable of a struct type using a struct literal like so - // Initialize a struct by supplying the value of all the struct fields. var p = Person.

Scene 23 (8m 28s)

Pointer to a struct You can get a pointer to a struct using the & operator. type Student struct func main() ps := &s // Pointer to the student struct fmt.Println ( ps ) fmt.Println ((* ps ).Name) // // Accessing struct fields via pointer fmt.Println ( ps.Name ) //same as bove ps.RollNumber = 31 fmt.Println (s) //should be very conscious while using pointer } Output: & Jack Jack &.

Scene 24 (8m 55s)

You can get a pointer to a struct using the new operator Package main import " fmt " type Employee struct func main() Output: &.

Scene 25 (9m 17s)

Functions. Functions and methods are both used extensively in Go to provide abstractions and make our programs easier tz read and reason about. On the surface, functions and methods both look similar, but there some important semantic differences which can make a big difference to the readability af your code„ In Golang, we declare a function using the func keyword.A function has a name, a list of comma- separated input parameters along with their types, the result type(s), and a body. Function Arguments and return type is optional. Following is an example of a simple function called avg that takes t-evo input parameters type float64 and returns the average of the inpu& The result is also of type float64 funcav x float64, float64 float64 { return x + / 2 Now, calling a function is very simple. You just need to pass the required number of parameters to the function like this - av 6.56, 13.44.

Scene 26 (9m 54s)

Example:- package main import " fmt " func avg ( x float64 , y float64 ) float64 func main () Output: Average of 5.75 and 6.25 = 6.00.

Scene 27 (10m 14s)

Functions with multiple return values Go functions are capable of returning multiple values. This is something that most programming languages don’t support natively. package main import " fmt " func fun(x, y int) (int, int) func main() Output: 10 20.

Scene 28 (10m 31s)

Method. A method is nothing but a function with a special receiver argument. The receiver argument has a name and a type. It appears between the func keyword and the method name - func ( receiver Type ) MethodName ( parameterList ) ( returnTypes ) Methods help you write object-oriented style code in Go. Moreover, Methods help you avoid naming conflicts. Since a method is tied to receiver , you can have the same method names on different receiver types..

Scene 29 (10m 51s)

type A struct func ( obj A) display() string type B struct func (obj1 B) display() string func main() obj1 := B fmt.Println ( obj.display ()) fmt.Println (obj1.display()) } Output: I am A struct I am B struct.

Scene 30 (11m 10s)

interface. An interface in Go is a type defined using a set of method signatures. The interface defines the behaviour for similar type of objects Typically, if you see a function or a method that expects an empty interface, then you can typically pass anything into this function/method. Example: package main import ( " fmt " ) func myFunc (a interface{}) func main() Output: 25.

Scene 31 (11m 31s)

A screenshot of a cell phone Description automatically generated.

Scene 32 (11m 38s)

Method Receiver types on Interface. Interface and value Receiver type User struct type Worker interface func (u User) Work() func DoWork (w Worker) func main() DoWork ( uval ) pval := &User DoWork ( pval ) } Output: UserVal has worked for 5 hrs. UserPtr has worked for 6 hrs..

Scene 33 (12m 1s)

Interface and pointer Receiver type User struct type Worker interface func (u *User) Work() func DoWork (w Worker) func main() DoWork ( uval ) pval := &User DoWork ( pval ) } Error// cannot use uval (type User) as type Worker in argument to DoWork : User does not implement Worker (Work method has pointer receiver).