- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang program to include a module inside the class
In Go programming language, a new module is initiated using init command after which we can import other modules in our code. There is no concept of class in Go, only structs are used. In this article, we will use one example to include a module inside the class. In this example, we will create a Circle struct whose area will be printed on the console. For this example, we will import math and fmt packages outside the struct but they can be used anywhere. The print statement is executed using Printf function from the fmt package.
Algorithm
Import the required modules in the program
Create a Circle struct with particular attributes like radius
A function is created to return the area of the circle
In main create the instance of the Circle and print the area of the circle
The area is printed using Printf function from the fmt package
Example 1
In this example, we created a Circle_area struct with contains the radius of the Circle. Then, Area method is created which returns the area of the circle. In the main, the instance of the Circle is created with radius value passed as 6. The area method is called and the area of circle is printed on the console using Printf from the fmt package. Here, the module is declared outside the struct and can be used anywhere.
//Golang program to include a module inside the class package main import ( "fmt" "math" ) //Create a Circle struct with radius attribute type Circle_area struct { radius float64 } func (c Circle_area) Area() float64 { return math.Pi * c.radius * c.radius //return the Area of the circle } //Create a main function to execute the program func main() { c := Circle_area{radius: 6} //Create a circle instance and provide the radius of the circle fmt.Printf("Circle area: %.2f\n", c.Area()) //Call the function and print the area of the circle }
Output
Circle area: 113.10
Conclusion
We executed and compiled the program of including a module inside the class using an example. In this example, we created a Circle struct and calculated its area, then printed it on the console. Hence, the program executed successfully.