How to create basic program in Golang

Hello, World! is the first basic program in any programming language. You can write this first program in Golang by following the steps below.

Hello, World! is the first basic program in any programming language. You can write this first program in Golang  by following the steps below.

First, open the Go compiler. In the Go language, programs are saved with the .go extension and are UTF-8 text files.
Now, first add the main package to your program:

package main

Every program must start with a package declaration . In Go, packages are used to organize and reuse code. In Go , there are two types of programs available, executables and libraries. Executables are programs that can be run directly from the terminal. Libraries are program packages that we can reuse in our programs. Here, the main package tells the compiler that the package should be compiled into an executable program, not a shared library. This is the starting point of the program and also contains the main function .

After adding main package import 'fmt' package to your program:

import( "fmt" )

Here, import keyword is used to import packages into the program and fmt package is used to implement formatted Input/Output using functions.

Now write code in main function to print hello world in Go language:

func main() { fmt.Println("!. Hello World .!") }

In the above lines of code, we have:

  1. func : Used to create functions in Go language.
  2. main : Is the main function in Go language, contains no parameters, does not return any values ​​and is called when you execute the program.
  3. Println() : This method is available in fmt package and is used to display the string ' !… Hello World …! '. Here, Println means Print line.

 

For example:

// Chương trình Go đầu tiên package main import "fmt"; // Hàm chính func main() { fmt.Println("!. Hello World .!") } 

Result:

!. Hello World .!

How to run Golang program

To run a Go program, you need a Go compiler. Once you have a Go compiler, first create a program and save your program with the .go extension , for example, first.go . Now we run this first.go file in the go compiler using the following command, i.e.:

$ go run first.go

How to create basic program in Golang Picture 1

4.5 ★ | 2 Vote