Write your first Go program:
In this tutorial, we will learn how to write a basic go program. This program will take one String as input from the user and print it back.
For Go programs, we need to write it in a file with extension .go. You can create a file with any name and run it.
Write a Go program:
Let’s create a file example.go and write the below code:
package main
import "fmt"
func main() {
fmt.Println("Hello World !!")
}
Here,
- main is the package of this program. We can have multiple files with the same package and each folder can have maximum of one package.
- import is used to import another package in a package. Here, we are importing fmt package, which is a go package. We will use this package to read text from the user and to print that text on console.
- fmt.Println is used to print something on console. We can pass one string to this method and it prints that value.
- main method is the entry point. It will first run the lines in this method.
Run the Go program:
To run the program, we can use go run command. Open a terminal, move to the folder that has this file and run the below command:
go run example.go
How to get user input:
The fmt modules provides methods to take a string as input from the user and put that in a variable. Using Println, we can print that variable back.
package main
import "fmt"
func main() {
var num int
fmt.Println("Enter a number: ")
fmt.Scanln(&num)
fmt.Println(num)
}
Here,
- We are using Scanln to read the user input value, i.e. a number.
- It reads the number and stores it in num
- The last Println statement prints the value of num.
It will print output as like below:
Enter a number:
12
12