# Trending December 2023 # Golang Program To Show Overriding Of Methods In Classes # Suggested January 2024 # Top 19 Popular

You are reading the article Golang Program To Show Overriding Of Methods In Classes updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Golang Program To Show Overriding Of Methods In Classes

When a method is overridden in Go, a new method with the same name and receiver type as an existing method is created and used in place of the existing one. As a result, Golang may provide polymorphism, allowing different implementations of a same method to be used depending on the type of receiver. Let’ see the execution in examples.

Method 1: Using shape struct

Here, this shape struct will contain an area field and an area method which will return the value of area field. Rectangle and square both inherit the area () method. The output will be their area printed on the console.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program

Step 2 − First, we create a struct Shape with a field called area of type float64 and a method called Area() that returns the field’s value.

Step 3 − The Shape struct is then embedded in a new structure called Rectangle, which also has two float64-type properties called width and height.

Step 4 − Then, we create a function for the Rectangle struct called CalculateArea() that computes the area using the width and height variables and assigns the result to the area field that was inherited from the Shape struct.

Step 5 − The Shape struct is also embedded in the Square struct, which similarly has a field side of type float64.

Step 6 − Then, using the side field to compute the area and assigning the result to the area field inherited from the Shape struct, we define the method CalculateArea() for the Square struct.

Step 7 − To compute the areas of the forms, we construct pointers to instances of the Rectangle and Square structs in the main function and call their respective CalculateArea() functions.

Step 8 − We invoke the Area() function on the Rectangle and Square pointers to obtain the areas of the forms after computing their areas.

Step 9 − The area of rectangle and the area of square is printed on the console using fmt.Println() function where ln means new line.

Example

In this example we will learn how to override methods in class using shape struct.

package main import ( "fmt" ) type Shape struct { area float64 } func (sq *Shape) Area() float64 { return chúng tôi } type Rectangle struct { Shape width float64 height float64 } func (rect *Rectangle) CalculateArea() { rect.area = rect.width * rect.height } type Square struct { Shape side float64 } func (sq *Square) CalculateArea() { sq.area = chúng tôi * chúng tôi } func main() { rect := &Rectangle{width: 16, height: 6} rect.CalculateArea() fmt.Println("Area of rectangle: ", rect.Area()) sq := &Square{side: 8} sq.CalculateArea() fmt.Println("Area of square: ", sq.Area()) } Output Area of rectangle: 96 Area of square: 64 Method 2: Using shape interface

Here, the shapes rectangle and square implement the shape interface by implementing the area method. In the end, the output will be the area of square and rectangle.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program

Step 2 − In the beginning, we create an interface called Shape with a function called Area() that returns a float64 value.

Step 3 − We then define a structure called Rectangle, which has two float64-type attributes called width and height.

Step 4 − The Area() method for the Rectangle struct is then implemented by creating a function with the same signature as the Shape interface and computing the area using the width and height parameters.

Step 5 − In a similar manner, we create a structure called Square with a field of type float64.

Step 6 − Then, using the side field to determine the area this time, we implement the Area() method for the Square struct.

Step 7 − The Rectangle struct’s Area() method is called in the main function, and it returns the area of the rectangle.

Step 8 − Additionally, we construct an instance of the Square struct and use its Area() method to obtain the square’s area.

Step 9 − The area of both the shapes is printed on the console using fmt.Println() function where ln means new line.

Example

In this example we will learn how to override methods in class using shape interface.

package main import ( "fmt" ) type Shape interface { Area() float64 } type Rectangle struct { width float64 height float64 } func (rect Rectangle) Area() float64 { return rect.width * rect.height } type Square struct { side float64 } func (sq Square) Area() float64 { return chúng tôi * chúng tôi } func main() { rect := Rectangle{width: 16, height: 6} fmt.Println("Area of rectangle: ", rect.Area()) sq := Square{side: 8} fmt.Println("Area of square: ", sq.Area()) } Output Area of rectangle: 96 Area of square: 64 Conclusion

We executed the program of showing how to override methods in class using two examples. In the first example we used shape struct and in the second example we used shape interface.

You're reading Golang Program To Show Overriding Of Methods In Classes

## Golang Program To Count Number Of Leaf Nodes In A Tree

In Go programming language, a tree is a data structure in which each node has a value and zero to many nodes as children. The root node is the node without a parent, while the leaf node is the node without children. Trees can be employed for a variety of tasks, including data storage, sorting, and searching in hierarchical structures. We will use two methods to count no. of leaf nodes in a tree. In the first method TreeNode struct is used whereas queue is used in the second example to execute the program.

Method 1: Using TreeNode Struct

This method implements the count_leaf_nodes function, which takes a root node as an argument and returns the number of leaf nodes in the tree. It also constructs a tree data structure using a TreeNode struct. The count_leaf_nodes function is invoked by the main function to count the leaf nodes of a sample tree that has been put up. The program will produce 4 as its output.

Algorithm

Step 1 − Create a package main and declare fmt(format package) and strings package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a struct called TreeNode that has fields for the node value and pointers to its left and right children to represent a node in the tree.

Step 3 − Create a function called count_leaf_nodes that takes a TreeNode pointer as an argument and returns the number of leaf nodes in the tree.

Step 4 − Verify whether the root node is nil in the count_leaf_nodes function. Return 0 if it is because there are no leaf nodes.

Step 5 − Check to see if the left and right children are nil if the root node is not nil. Return 1 if they are, as this node is a leaf node.

Step 6 − Recursively call countLeafNodes on the left and right children if they are not null, and then return the total of the two results.

Step 7 − Create a TreeNode struct instance in the main function to represent the tree’s root node, and set its left and right children to other TreeNode struct instances to represent the rest of the tree.

Step 8 − Use the root node as a parameter when calling the count_leaf_nodes method. The number of leaf nodes in the tree will be the function’s output.

Example

In this example, we will use TreeNode struct to implement no. of leaf nodes in a tree.

package main import "fmt" type TreeNode struct { Val int Left_val *TreeNode Right_val *TreeNode } func count_leaf_nodes(root *TreeNode) int { if root == nil { return 0 } if root.Left_val == nil && root.Right_val == nil { return 1 } return count_leaf_nodes(root.Left_val) + count_leaf_nodes(root.Right_val) } func main() { root := &TreeNode{Val: 10, Left_val: &TreeNode{Val: 20, Left_val: &TreeNode{Val: 40, Left_val: nil, Right_val: nil, }, Right_val: &TreeNode{Val: 50, Left_val: nil, Right_val: nil, }, }, Right_val: &TreeNode{Val: 30, Left_val: &TreeNode{Val: 60, Left_val: nil, Right_val: nil, }, Right_val: &TreeNode{Val: 70, Left_val: nil, Right_val: nil, }, }, } fmt.Println("The total no. of leaf nodes in the tree are:") fmt.Println(count_leaf_nodes(root)) } Output The total no. of leaf nodes in the tree are: 4 Method 2: Using queue to count no. of leaf nodes in a tree

This method tracks the next nodes to visit using a queue. When adding nodes to the queue, it begins by adding the root node. Then, it repeatedly takes the next node from the front, determines whether it is a leaf node (that is, if its left and right children are nil), and adds its children to the back of the queue if they are not nil. A count variable, which is increased each time a leaf node is encountered, is used to keep track of the number of leaf nodes. After visiting each node, the function returns the count.

Algorithm

Step 1 − Create a package main and declare fmt(format package) and strings package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a struct called TreeNode that has fields for the node value and pointers to its left and right children to represent a node in the tree.

Step 3 − Create a function called count_leaf_nodes that takes a TreeNode pointer as an argument and returns the number of leaf nodes in the tree.

Step 4 − Create a queue and set its root node and count to 0.

Step 5 −

a. Dequeue the initial node from the queue while it still contains nodes.

b. Increase the count if the dequeued node is a leaf node (that is, if its left and right children are nil).

c. Enqueue the left child of the dequeued node if it is not null.

d. Enqueue the right child of the dequeued node if it is not null.

Step 6 − Return the count to the function.

Step 7 − Create a TreeNode struct instance in the main function to represent the tree’s root node, and set its left and right children to other TreeNode struct instances to represent the rest of the tree.

Example

In this example we will use queue data structure to implement the program.

package main import "fmt" type TreeNode struct { Val int Left_val *TreeNode Right_val *TreeNode } func count_leaf_nodes(root *TreeNode) int { if root == nil { return 0 } queue := []*TreeNode{root} count := 0 node := queue[0] queue = queue[1:] if node.Left_val == nil && node.Right_val == nil { count++ } if node.Left_val != nil { queue = append(queue, node.Left_val) } if node.Right_val != nil { queue = append(queue, node.Right_val) } } return count } func main() { root := &TreeNode{Val: 1, Left_val: &TreeNode{Val: 2, Left_val: &TreeNode{Val: 4, Left_val: nil, Right_val: nil, }, Right_val: &TreeNode{Val: 5, Left_val: nil, Right_val: nil, }, }, Right_val: &TreeNode{Val: 3, Left_val: &TreeNode{Val: 6, Left_val: nil, Right_val: nil, }, Right_val: &TreeNode{Val: 7, Left_val: nil, Right_val: nil, }, }, } fmt.Println("The no. of leaf nodes in the tree are:") fmt.Println(count_leaf_nodes(root)) } Output The no. of leaf nodes in the tree are: 4 Conclusion

We executed the program of counting no. of leaf nodes in a tree using two examples. In the first example we used the tree data structure using TreeNode struct and in the second example we used queue data structure to execute the program.

## Golang Program To Create Directories

Golang has internal packages like os and io packages for creating a new directory. Here, we will create a directory using two examples. In the first example we will use os.Mkdir function and in the second example we will use ioutil.WriteFile function to execute the program.

Method 1: Using os.Mkdir Function

In this method, a directory named dirName variable is created using the os.Mkdir function. The permission bits for the new directory are the second input to os.Mkdir, which we set to 0755. (read, write, and execute permissions for the owner and read and execute permissions for others). The program will print “Directory created successfully!” if the directory creation is successful otherwise it will produce an error message.

Syntax os.Mkdir()

The os.Mkdir function in Go helps in creating a new directory with the specified name and permission bits (mode).

Algorithm

Step 1 − Create a package main and declare fmt(format package),and os package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a directoryname variable and assign it to the newdir one wants to create.

Step 3 − Use os.Mkdir function to create a new directory.

Step 4 − If an error persists while creating the directory, print the error on the console using fmt.Println() function where ln means new line and return.

Step 5 − If the directory is created successfully, Print the success message using the statement used in Step4.

Example

In this example we will use os.Mkdir function to create new directory.

package main import ( "fmt" "os" ) func main() { directoryname := "newdir" err := os.Mkdir(directoryname, 0755) if err != nil { fmt.Println(err) return } fmt.Println("Directory created successfully!") } Output Directory created successfully! Method 2: Using io/ioutil Package

In this method, an empty file with the name and permission bits is created using the ioutil.WriteFile function. If the function returns a nil error and the file is successfully created, we will print success. The WriteFile function will create the directory and if an error comes while creating a directory, we will print the error message.

Syntax Ioutil.WriteFile()

The ioutil.WriteFile function in Go is used to write a byte slice to a file.

Algorithm

Step 1 − Create a package main and declare fmt(format package), io/ioutil package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create the function main and in that function create a variable directoryname and assign it to newdir.

Step 3 − Use ioutil package function iouti.WriteFile function to create a directory.

Step 4 − If an error comes while creating the directory, print the error on the console and return.

Step 5 − If the directory is created successfully, print the success statement on the console.

Step 6 − The print statement is executed fmt.Println() function where ln means new line.

Example

In this example, we will use io/ioutil package function to create new directory.

package main import ( "fmt" "io/ioutil" ) func main() { directoryname := "newdir" err := ioutil.WriteFile(directoryname, []byte(""), 0755) if err != nil { fmt.Println(err) return } fmt.Println("Directory created successfully!") } Output Directory created successfully! Conclusion

We executed the program of creating a directory using two methods. In the first method we used os.Mkdir function and in the second method we used io/ioutil package to execute the program.

## Golang Program To Compare Elements In Two Slices

In this tutorial, we will learn how to compare elements in two slices. In slices a simple equality comparison is not possible so the slices are compared with their lengths and the elements present in the loop. The output will be printed in the form of Boolean value on the console with the help of fmt.Println() function. Let’s see how to execute this with the help of an example.

Method 1: Using a user-defined function

In this method, we will compare elements in two slices using an external function and, in that function, we will set some conditions, if the slices satisfy those conditions, they will be considered equal else they won’t be considered equal. Let’s have a look to get a better understanding.

Syntax func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and import fmt package in the program.

Step 2 − Create a main function, in it create two slices of type string and call a function named slice_equality with two slices as arguments.

Step 3 − Create a function slice_equality and in that function check if the length of the first slice is not equal to the second slice return false.

Step 4 − In the next case run a for loop till the range of str1 and check if the elements of str2 are equal to str1, if they are not equal return false.

Step 5 − After checking all the conditions set in the algorithm, if not even once false is returned, return true to the function.

Step 6 − Print the Boolean value using fmt.Println() function where ln refers to the next line here.

Example

Golang program to compare elements in two slices using custom function

package main import "fmt" func slice_equality(str1, str2 []string) bool { if len(str1) != len(str2) { return false } for i, str := range str1 { if str != str2[i] { return false } } return true } func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The slices are equal or not before adding any element:") fmt.Println(slice_equality(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The slices are equal or not after adding another element:") fmt.Println(slice_equality(str1, str2)) } Output The slices are equal or not before adding any element: true The slices are equal or not after adding another element: false Method 2: Using built-in function

In this method, we will use reflect.DeepEqual() function to compare two slices recursively. Built-in functions ease our work and shorten the code. The output here will be printed using fmt.Println() function. Let’s have a look and inculcate how to solve this problem.

Syntax reflect.DeepEqual()

This function compares two values recursively. It traverses and check the equality of the corresponding data values at each level. However, the solution is less safe as compared to comparison in loops. Reflect should be used with care and should be used in those cases where it’s of utmost importance.

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and import fmt and reflect package in the program.

Step 2 − Create a function main and in that function create two slices of type string which are to be compared with each other.

Step 3 − In the first case before adding any new element in the slice, compare the slices using reflect.DeepEqual() function with the slices as parameters.

Step 4 − In the second case add new string in the slice and compare the slices using reflect.DeepEqual() function with the slices as parameters.

Step 5 − The output will be printed using fmt.Prinln() function on the console as a Boolean value.

Example

Golang program to compare elements in two slices using built-in function

package main import ( "fmt" "reflect" ) func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The strings are equal or not before adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The strings are equal or not after adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) } Output The strings are equal or not before adding any element: true The strings are equal or not after adding any element: false Conclusion

In this tutorial, of comparing slices, we used two methods to execute the program. In the first method we used custom function with some conditions and in the second method we used a built-in function named reflect.DeepEqual() function.

## Golang Program To Calculate The Sum Of Columns Of Matrix Elements

A matrix is a collection of numbers arranged in rows and columns, a two-dimensional array, each of the values of this matrix is known as an element. Here we will use three methods to find the sum of column elements and compare each method for the same using go programming.

Here is an example of a matrix and the sum value of it’s columns −

The given matrix is −

0 1 2 4 5 6 8 9 7

Sum of elements in column 1 is 12

Sum of elements in column 2 is 15

Sum of elements in column 3 is 15

Algorithm

Step 1 − Import the fmt package.

Step 2 − Now we need to start the main() function.

Step 3 − Then we are creating a matrix naming matrix and assign elements to it.

Step 4 − Print the matrix on the screen using fmt.Println() function.

Step 5 − Initialize a new variable called sum of type int to hold the resultant sum.

Step 6 − To find sum of the column elements use the for loop to iterate over the matrix.

Step 7 − Using the first for loop is used to get the column of the matrix while the second for loop gives us the column of the matrix.

Step 8 − Once the loop gets over the matrix elements update the sum variable by adding values to it.

Step 9 − Print the sum of the matrix on the screen.

Example 1

In the following example, we will use a for loop to iterate over the matrix and find the sum of its elements and print it on the screen.

package main import "fmt" func main() { matrix := [][]int{ {0, 1, 2}, {4, 5, 6}, {8, 9, 7}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix[0]); i++ { sum := 0 for j := 0; j < len(matrix); j++ { sum += matrix[j][i] } fmt.Printf("Sum of elements in column %d is %dn", i+1, sum) } } Output The given matrix is: 0 1 2 4 5 6 8 9 7 Sum of elements in column 1 is 12 Sum of elements in column 2 is 15 Sum of elements in column 3 is 15 Example 2

In this example we will find the sum of the columns of matrix elements using range function.

package main import "fmt" func main() { matrix := [][]int{ {10, 1, 2}, {4, 50, 6}, {8, 9, 7}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix[0]); i++ { sum := 0 for _, row := range matrix { sum += row[i] } fmt.Printf("Sum of elements in column %d is %dn", i+1, sum) } } Output The given matrix is: 10 1 2 4 50 6 8 9 7 Sum of elements in column 1 is 22 Sum of elements in column 2 is 60 Sum of elements in column 3 is 15 Example 3

In this example we will use the recursion approach to find the sum of columns of matrix elements.

package main import "fmt" func colSum(matrix [][]int, col int) int { if col == len(matrix[0]) { return 0 } sum := 0 for i := range matrix { sum += matrix[i][col] } return sum } func main() { matrix := [][]int{ {20, 1, 22}, {43, 5, 16}, {86, 91, 10}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix[0]); i++ { fmt.Printf("Sum of elements in column %d is %dn", i+1, colSum(matrix, i)) } } Output The given matrix is: 20 1 22 43 5 16 86 91 10 Sum of elements in column 1 is 149 Sum of elements in column 2 is 97 Sum of elements in column 3 is 48 Conclusion

We have successfully compiled and executed a go language program to calculate the sum of columns of matrix elements along with examples. In the first and second example we have used for loop and range functions respectively in the main() section of the program while in the last example we have used a separate function to implement the logic.

## Golang Program To Get The Middle Element Of Linkedlist In A Single Iteration

In golang data structures , a linked list has pointers connecting the items, and from the first node (head) to the last node, each node can be visited (tail) using next pointer. We will obtain the middle element of a linked list using two methods. The first approach depicts use of two-pointer approach and the second approach uses a counter variable to execute the program.

Method 1: Using two-pointer approach

In this method, the function navigates the linked list using two pointers, low and high. The high pointer takes two steps at a time, whereas the low pointer takes one step. The low pointer will be pointing to the middle member of the linked list when the high pointer reaches the end of the list.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a node struct with values of type int and next of type node.

Step 3 − Create a function middle_node and in that function further create two pointers, low and high, and set them both to point to the linked list’s head.

Step 4 − Until high reaches the end of the list, iterate through the linked list.

Step 5 − Move the low pointer one step and the high pointer two steps in each cycle.

Step 6 − The low pointer will be pointing to the middle member of the linked list when the high pointer reaches the end of the list.

Step 7 − In the next step, return the low pointer back to the function.

Step 8 − This approach works because the middle element will be pointed to by the low pointer when the high pointer reaches the end of the list for a linked list with an odd number of entries. The low pointer will be pointing to the middle element of the two middle elements for a linked list with an even number of entries.

Example

In this example we used two pointer approach to get the middle element from the linked list.

package main import "fmt" type Node struct { value int next *Node } func middle_node(head *Node) *Node { low, high := head, head for high != nil && chúng tôi != nil { low = low.next high = high.next.next } return low } func main() { head := &Node{value: 10} chúng tôi = &Node{value: 20} chúng tôi = &Node{value: 30} chúng tôi = &Node{value: 40} chúng tôi = &Node{value: 50} node := middle_node(head) fmt.Println("The middle node in the linked list is:", node.value) } Output The middle node in the linked list is: 30 Method 2: Using counter variable Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a node struct with values of type int and next of type node.

Step 3 − Create a function middle_node and in that particular function initialize a counter variable to 0 and a pointer node pointing to the head of the linked list.

Step 4 − Iterate through the linked list, incrementing the counter for each node and moving node to the next node until node reaches the end of the list.

Step 5 − Initialize node to the head of the linked list again.

Step 6 − Iterate count/2 times, moving node to the next node each time.

Step 7 − Return node, which will be pointing to the middle element of the linked list.

Step 8 − Print the node received in main function using fmt.Println() function where ln means new line.

Example

In this example we will use counter variable to find the middle element from the linked list.

package main import "fmt" type Node struct { value int next *Node } func middle_node(head *Node) *Node { count := 0 node := head for node != nil { count++ node = node.next } node = head for i := 0; i < count/2; i++ { node = node.next } return node } func main() { head := &Node{value: 10} chúng tôi = &Node{value: 20} chúng tôi = &Node{value: 30} chúng tôi = &Node{value: 40} chúng tôi = &Node{value: 50} node := middle_node(head) fmt.Println("The middle node in the linked list is:", node.value) } Output The middle node in the linked list is: 30 Conclusion

We executed the program of getting the middle element of a linked list in single iteration using two methods. In the first method we used two pointer approach and in the second example we used counter variable to keep track of elements of linked list.

Update the detailed information about Golang Program To Show Overriding Of Methods In Classes on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!