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.
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:
- func : Used to create functions in Go language.
- main : Is the main function in Go language, contains no parameters, does not return any values and is called when you execute the program.
- 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
You should read it
- What is Golang? Things you need to know about Golang programming language
- What is GoLang? How to install GoLang on Windows 10
- How to Install Go on Windows
- How to implement a graph data structure in Golang
- 10 programming languages booming today
- The development flow of programming languages, new problems that are not new
- Do you know what programming language is?
- Udemy's top 5 JavaScript courses
- What is the first programming language in the world?
- In the end, big universities realized that Java was a lousy language if used for introductory programming
- Overview of R language, install R on Windows and Linux
- How to Learn a Programming Language