Golang program to create a module with variables


In golang we can create a module with variable using const or var keywords, orelse we can even import the module . A module in Go is a group of packages. It helps in managing the distribution of the package.

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 − In the first step, create three variables name, age and address using var keyword and assign these variables the desired values.

  • Step 3 − Then, create a main function and in that function print the name, age and address variable using Println from fmt package.

  • Step 4 − Here, the print statement is executed using fmt.Println() function where ln means new line.

Example 1

In this example, we will write a Golang program to create a module using var keyword to declare name variable of type string, age of type int and address of type string and then in the main function we will print the value of the variables using fmt package.

package main

import "fmt" 

var (
   name string = "Rupesh Kriplani"    
   age int   = 60          
   address string = "624 Connaught place"  
)

//create main to print variables    
func main() {
   fmt.Println("Name:", name)  
   fmt.Println("Age:", age)        
   fmt.Println("Address:", address) 
}

Output

Name: Rupesh Kriplani
Age: 60
Address: 624 Cannaught place

Example 2

In this illustration, const keyword is primarily used to create a module with variables. We have executed it similarly just like the previous example but the main difference is usage of const keyword.

package main
import (
   "fmt" 
)

const (
   name    = "Rahul kukreja"  
   age     = 40                         
   address = "684 Dwarka New Delhi" 
)

func main() {
   fmt.Println("Name:", name) 
   fmt.Println("Age:", age)       
   fmt.Println("Address:", address) 
}

Output

Name: Rahul kukreja
Age: 40
Address: 684 Dwarka New Delhi

Example 3

In this example, we will write a Golang program to create a module using the importing of module in the file where main function is executed.

package mymodule
var str1 string = "Hello, alexa!"
var num1 int = 20

package main

import (
   "fmt"
   "mymodule"
)
func main() {
   fmt.Println(mymodule.str1)
   fmt.Println(mymodule.num1)
}

Output

Hello, alexa!
20

Conclusion

In this program we created a module with variables using three examples. In the first example we have used a var keyword to create variables for the module, in the second example we used a const keyword to execute the program respectively and in the third example, we imported a module in the file where main function is executed and the variables are called using dot notation.

Updated on: 04-Apr-2023

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements