Go – Structures ”; Previous Next Go arrays allow you to define variables that can hold several data items of the same kind. Structure is another user-defined data type available in Go programming, which allows you to combine data items of different kinds. Structures are used to represent a record. Suppose you want to keep track of the books in a library. You might want to track the following attributes of each book − Title Author Subject Book ID In such a scenario, structures are highly useful. Defining a Structure To define a structure, you must use type and struct statements. The struct statement defines a new data type, with multiple members for your program. The type statement binds a name with the type which is struct in our case. The format of the struct statement is as follows − type struct_variable_type struct { member definition; member definition; … member definition; } Once a structure type is defined, it can be used to declare variables of that type using the following syntax. variable_name := structure_variable_type {value1, value2…valuen} Accessing Structure Members To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. The following example explains how to use a structure − Live Demo package main import “fmt” type Books struct { title string author string subject string book_id int } func main() { var Book1 Books /* Declare Book1 of type Book */ var Book2 Books /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = “Go Programming” Book1.author = “Mahesh Kumar” Book1.subject = “Go Programming Tutorial” Book1.book_id = 6495407 /* book 2 specification */ Book2.title = “Telecom Billing” Book2.author = “Zara Ali” Book2.subject = “Telecom Billing Tutorial” Book2.book_id = 6495700 /* print Book1 info */ fmt.Printf( “Book 1 title : %sn”, Book1.title) fmt.Printf( “Book 1 author : %sn”, Book1.author) fmt.Printf( “Book 1 subject : %sn”, Book1.subject) fmt.Printf( “Book 1 book_id : %dn”, Book1.book_id) /* print Book2 info */ fmt.Printf( “Book 2 title : %sn”, Book2.title) fmt.Printf( “Book 2 author : %sn”, Book2.author) fmt.Printf( “Book 2 subject : %sn”, Book2.subject) fmt.Printf( “Book 2 book_id : %dn”, Book2.book_id) } When the above code is compiled and executed, it produces the following result − Book 1 title : Go Programming Book 1 author : Mahesh Kumar Book 1 subject : Go Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 Structures as Function Arguments You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the same way as you did in the above example − Live Demo package main import “fmt” type Books struct { title string author string subject string book_id int } func main() { var Book1 Books /* Declare Book1 of type Book */ var Book2 Books /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = “Go Programming” Book1.author = “Mahesh Kumar” Book1.subject = “Go Programming Tutorial” Book1.book_id = 6495407 /* book 2 specification */ Book2.title = “Telecom Billing” Book2.author = “Zara Ali” Book2.subject = “Telecom Billing Tutorial” Book2.book_id = 6495700 /* print Book1 info */ printBook(Book1) /* print Book2 info */ printBook(Book2) } func printBook( book Books ) { fmt.Printf( “Book title : %sn”, book.title); fmt.Printf( “Book author : %sn”, book.author); fmt.Printf( “Book subject : %sn”, book.subject); fmt.Printf( “Book book_id : %dn”, book.book_id); } When the above code is compiled and executed, it produces the following result − Book title : Go Programming Book author : Mahesh Kumar Book subject : Go Programming Tutorial Book book_id : 6495407 Book title : Telecom Billing Book author : Zara Ali Book subject : Telecom Billing Tutorial Book book_id : 6495700 Pointers to Structures You can define pointers to structures in the same way as you define pointer to any other variable as follows − var struct_pointer *Books Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure”s name as follows − struct_pointer = &Book1; To access the members of a structure using a pointer to that structure, you must use the “.” operator as follows − struct_pointer.title; Let us re-write the above example using structure pointer − Live Demo package main import “fmt” type Books struct { title string author string subject string book_id int } func main() { var Book1 Books /* Declare Book1 of type Book */ var Book2 Books /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = “Go Programming” Book1.author = “Mahesh Kumar” Book1.subject = “Go Programming Tutorial” Book1.book_id = 6495407 /* book 2 specification */ Book2.title = “Telecom Billing” Book2.author = “Zara Ali” Book2.subject = “Telecom Billing Tutorial” Book2.book_id = 6495700 /* print Book1 info */ printBook(&Book1) /* print Book2 info */ printBook(&Book2) } func printBook( book *Books ) { fmt.Printf( “Book title : %sn”, book.title); fmt.Printf( “Book author : %sn”, book.author); fmt.Printf( “Book subject : %sn”, book.subject); fmt.Printf( “Book book_id : %dn”, book.book_id); } When the above code is compiled and executed, it produces the following result − Book title : Go Programming Book author : Mahesh Kumar Book subject : Go Programming Tutorial Book book_id : 6495407 Book title : Telecom Billing Book author : Zara Ali Book subject : Telecom Billing Tutorial Book book_id : 6495700 Print Page Previous Next Advertisements ”;
Category: go
Go – Functions
Go – Functions ”; Previous Next A function is a group of statements that together perform a task. Every Go program has at least one function, which is main(). You can divide your code into separate functions. How you divide your code among different functions is up to you, but logically, the division should be such that each function performs a specific task. A function declaration tells the compiler about a function name, return type, and parameters. A function definition provides the actual body of the function. The Go standard library provides numerous built-in functions that your program can call. For example, the function len() takes arguments of various types and returns the length of the type. If a string is passed to it, the function returns the length of the string in bytes. If an array is passed to it, the function returns the length of the array. Functions are also known as method, sub-routine, or procedure. Defining a Function The general form of a function definition in Go programming language is as follows − func function_name( [parameter list] ) [return_types] { body of the function } A function definition in Go programming language consists of a function header and a function body. Here are all the parts of a function − Func − It starts the declaration of a function. Function Name − It is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required. Function Body − It contains a collection of statements that define what the function does. Example The following source code shows a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two − /* function returning the max between two numbers */ func max(num1, num2 int) int { /* local variable declaration */ result int if (num1 > num2) { result = num1 } else { result = num2 } return result } Calling a Function While creating a Go function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program. To call a function, you simply need to pass the required parameters along with its function name. If the function returns a value, then you can store the returned value. For example − Live Demo package main import “fmt” func main() { /* local variable definition */ var a int = 100 var b int = 200 var ret int /* calling a function to get max value */ ret = max(a, b) fmt.Printf( “Max value is : %dn”, ret ) } /* function returning the max between two numbers */ func max(num1, num2 int) int { /* local variable declaration */ var result int if (num1 > num2) { result = num1 } else { result = num2 } return result } We have kept the max() function along with the main() function and compiled the source code. While running the final executable, it would produce the following result − Max value is : 200 Returning multiple values from Function A Go function can return multiple values. For example − Live Demo package main import “fmt” func swap(x, y string) (string, string) { return y, x } func main() { a, b := swap(“Mahesh”, “Kumar”) fmt.Println(a, b) } When the above code is compiled and executed, it produces the following result − Kumar Mahesh Function Arguments If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways that arguments can be passed to a function − Sr.No Call Type & Description 1 Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. 2 Call by reference This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. By default, Go uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. The above program, while calling the max() function, used the same method. Function Usage A function can be used in the following ways: Sr.No Function Usage & Description 1 Function as Value Functions can be created on the fly and can be used as values. 2 Function Closures Functions closures are anonymous functions and can be used in dynamic programming. 3 Method Methods are special functions with a receiver. Print Page Previous Next
Go – Interfaces
Go – Interfaces ”; Previous Next Go programming provides another data type called interfaces which represents a set of method signatures. The struct data type implements these interfaces to have method definitions for the method signature of the interfaces. Syntax /* define an interface */ type interface_name interface { method_name1 [return_type] method_name2 [return_type] method_name3 [return_type] … method_namen [return_type] } /* define a struct */ type struct_name struct { /* variables */ } /* implement interface methods*/ func (struct_name_variable struct_name) method_name1() [return_type] { /* method implementation */ } … func (struct_name_variable struct_name) method_namen() [return_type] { /* method implementation */ } Example Live Demo package main import (“fmt” “math”) /* define an interface */ type Shape interface { area() float64 } /* define a circle */ type Circle struct { x,y,radius float64 } /* define a rectangle */ type Rectangle struct { width, height float64 } /* define a method for circle (implementation of Shape.area())*/ func(circle Circle) area() float64 { return math.Pi * circle.radius * circle.radius } /* define a method for rectangle (implementation of Shape.area())*/ func(rect Rectangle) area() float64 { return rect.width * rect.height } /* define a method for shape */ func getArea(shape Shape) float64 { return shape.area() } func main() { circle := Circle{x:0,y:0,radius:5} rectangle := Rectangle {width:10, height:5} fmt.Printf(“Circle area: %fn”,getArea(circle)) fmt.Printf(“Rectangle area: %fn”,getArea(rectangle)) } When the above code is compiled and executed, it produces the following result − Circle area: 78.539816 Rectangle area: 50.000000 Print Page Previous Next Advertisements ”;
Go – Decision Making
Go – Decision Making ”; Previous Next Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Go programming language provides the following types of decision making statements. Click the following links to check their detail. Sr.No Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. 3 nested if statements You can use one if or else if statement inside another if or else if statement(s). 4 switch statement A switch statement allows a variable to be tested for equality against a list of values. 5 select statement A select statement is similar to switch statement with difference that case statements refers to channel communications. Print Page Previous Next Advertisements ”;
Go – Questions and Answers
Go Questions and Answers ”; Previous Next Go Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. Sr.No Question/Answers Type 1 Go Interview Questions This section provides a huge collection of Go Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Go Online Quiz This section provides a great collection of Go Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Go Online Test If you are preparing to appear for a Java and Go related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Go Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;
Go – Loops
Go – Loops ”; Previous Next There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Go programming language provides the following types of loop to handle looping requirements. Sr.No Loop Type & Description 1 for loop It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 2 nested loops These are one or multiple loops inside any for loop. Loop Control Statements Loop control statements change an execution from its normal sequence. When an execution leaves its scope, all automatic objects that were created in that scope are destroyed. Go supports the following control statements − Sr.No Control Statement & Description 1 break statement It terminates a for loop or switch statement and transfers execution to the statement immediately following the for loop or switch. 2 continue statement It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 3 goto statement It transfers control to the labeled statement. The Infinite Loop A loop becomes an infinite loop if its condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty or by passing true to it. package main import “fmt” func main() { for true { fmt.Printf(“This loop will run forever.n”); } } When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop. Note − You can terminate an infinite loop by pressing Ctrl + C keys. Print Page Previous Next Advertisements ”;
Go – Range
Go – Range ”; Previous Next The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table. Range expression 1st Value 2nd Value(Optional) Array or slice a [n]E index i int a[i] E String s string type index i int rune int map m map[K]V key k K value m[k] V channel c chan E element e E none Example The following paragraph shows how to use range − Live Demo package main import “fmt” func main() { /* create a slice */ numbers := []int{0,1,2,3,4,5,6,7,8} /* print the numbers */ for i:= range numbers { fmt.Println(“Slice item”,i,”is”,numbers[i]) } /* create a map*/ countryCapitalMap := map[string] string {“France”:”Paris”,”Italy”:”Rome”,”Japan”:”Tokyo”} /* print map using keys*/ for country := range countryCapitalMap { fmt.Println(“Capital of”,country,”is”,countryCapitalMap[country]) } /* print map using key-value*/ for country,capital := range countryCapitalMap { fmt.Println(“Capital of”,country,”is”,capital) } } When the above code is compiled and executed, it produces the following result − Slice item 0 is 0 Slice item 1 is 1 Slice item 2 is 2 Slice item 3 is 3 Slice item 4 is 4 Slice item 5 is 5 Slice item 6 is 6 Slice item 7 is 7 Slice item 8 is 8 Capital of France is Paris Capital of Italy is Rome Capital of Japan is Tokyo Capital of France is Paris Capital of Italy is Rome Capital of Japan is Tokyo Print Page Previous Next Advertisements ”;
Go – Arrays
Go – Arrays ”; Previous Next Go programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array in Go, a programmer specifies the type of the elements and the number of elements required by an array as follows − var variable_name [SIZE] variable_type This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Go data type. For example, to declare a 10-element array called balance of type float32, use this statement − var balance [10] float32 Here, balance is a variable array that can hold up to 10 float numbers. Initializing Arrays You can initialize array in Go either one by one or using a single statement as follows − var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0} The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0} You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array − balance[4] = 50.0 The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called base index and last index of an array will be total size of the array minus 1. Following is the pictorial representation of the same array we discussed above − Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − float32 salary = balance[9] The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays − Live Demo package main import “fmt” func main() { var n [10]int /* n is an array of 10 integers */ var i,j int /* initialize elements of array n to 0 */ for i = 0; i < 10; i++ { n[i] = i + 100 /* set element at location i to i + 100 */ } /* output each array element”s value */ for j = 0; j < 10; j++ { fmt.Printf(“Element[%d] = %dn”, j, n[j] ) } } When the above code is compiled and executed, it produces the following result − Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Go Arrays in Detail There are important concepts related to array which should be clear to a Go programmer − Sr.No Concept & Description 1 Multi-dimensional arrays Go supports multidimensional arrays. The simplest form of a multidimensional array is the two-dimensional array. 2 Passing arrays to functions You can pass to the function a pointer to an array by specifying the array”s name without an index. Print Page Previous Next Advertisements ”;
Go – Maps
Go – Maps ”; Previous Next Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. Defining a Map You must use make function to create a map. /* declare a variable, by default map will be nil*/ var map_variable map[key_data_type]value_data_type /* define the map as nil map can not be assigned any value*/ map_variable = make(map[key_data_type]value_data_type) Example The following example illustrates how to create and use a map − Live Demo package main import “fmt” func main() { var countryCapitalMap map[string]string /* create a map*/ countryCapitalMap = make(map[string]string) /* insert key-value pairs in the map*/ countryCapitalMap[“France”] = “Paris” countryCapitalMap[“Italy”] = “Rome” countryCapitalMap[“Japan”] = “Tokyo” countryCapitalMap[“India”] = “New Delhi” /* print map using keys*/ for country := range countryCapitalMap { fmt.Println(“Capital of”,country,”is”,countryCapitalMap[country]) } /* test if entry is present in the map or not*/ capital, ok := countryCapitalMap[“United States”] /* if ok is true, entry is present otherwise entry is absent*/ if(ok){ fmt.Println(“Capital of United States is”, capital) } else { fmt.Println(“Capital of United States is not present”) } } When the above code is compiled and executed, it produces the following result − Capital of India is New Delhi Capital of France is Paris Capital of Italy is Rome Capital of Japan is Tokyo Capital of United States is not present delete() Function delete() function is used to delete an entry from a map. It requires the map and the corresponding key which is to be deleted. For example − Live Demo package main import “fmt” func main() { /* create a map*/ countryCapitalMap := map[string] string {“France”:”Paris”,”Italy”:”Rome”,”Japan”:”Tokyo”,”India”:”New Delhi”} fmt.Println(“Original map”) /* print map */ for country := range countryCapitalMap { fmt.Println(“Capital of”,country,”is”,countryCapitalMap[country]) } /* delete an entry */ delete(countryCapitalMap,”France”); fmt.Println(“Entry for France is deleted”) fmt.Println(“Updated map”) /* print map */ for country := range countryCapitalMap { fmt.Println(“Capital of”,country,”is”,countryCapitalMap[country]) } } When the above code is compiled and executed, it produces the following result − Original Map Capital of France is Paris Capital of Italy is Rome Capital of Japan is Tokyo Capital of India is New Delhi Entry for France is deleted Updated Map Capital of India is New Delhi Capital of Italy is Rome Capital of Japan is Tokyo Print Page Previous Next Advertisements ”;
Go – Program Structure
Go – Program Structure ”; Previous Next Before we study the basic building blocks of Go programming language, let us first discuss the bare minimum structure of Go programs so that we can take it as a reference in subsequent chapters. Hello World Example A Go program basically consists of the following parts − Package Declaration Import Packages Functions Variables Statements and Expressions Comments Let us look at a simple code that would print the words “Hello World” − Live Demo package main import “fmt” func main() { /* This is my first sample program. */ fmt.Println(“Hello, World!”) } Let us take a look at the various parts of the above program − The first line of the program package main defines the package name in which this program should lie. It is a mandatory statement, as Go programs run in packages. The main package is the starting point to run the program. Each package has a path and name associated with it. The next line import “fmt” is a preprocessor command which tells the Go compiler to include the files lying in the package fmt. The next line func main() is the main function where the program execution begins. The next line /*…*/ is ignored by the compiler and it is there to add comments in the program. Comments are also represented using // similar to Java or C++ comments. The next line fmt.Println(…) is another function available in Go which causes the message “Hello, World!” to be displayed on the screen. Here fmt package has exported Println method which is used to display the message on the screen. Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means the function or variable/constant is accessible to the importer of the respective package. Executing a Go Program Let us discuss how to save the source code in a file, compile it, and finally execute the program. Please follow the steps given below − Open a text editor and add the above-mentioned code. Save the file as hello.go Open the command prompt. Go to the directory where you saved the file. Type go run hello.go and press enter to run your code. If there are no errors in your code, then you will see “Hello World!” printed on the screen. $ go run hello.go Hello, World! Make sure the Go compiler is in your path and that you are running it in the directory containing the source file hello.go. Print Page Previous Next Advertisements ”;