Thứ Bảy, Tháng Ba 15, 2025
spot_img
HomeHow to create basic programs in Golang

How to create basic programs in Golang

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

First, open the Go compiler. In Go language, programs are saved with the extension .go and is a UTF-8 text file.
Now, let's add the package first main. main into your program:

package main

Every program must begin with a declaration package. package. In the Go language, the package. package used to organize and reuse code. In Gothere are two types of programs available, one is an executable program and the other is a library. Executable programs are those that can be run directly from terminal. terminal. Libraries are program packages that we can reuse them in our programs. Here, package main tells the compiler that the package must compile into an executable, not a shared library. This is the starting point of the program and also contains the function main. main in there.

After adding main package import “fmt” package into your program:

import(
"fmt"
)

Here, the keyword import used for importing packages into programs and packages fmt used to implement Input/Output formatted with functions.

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

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

In the lines of code above, we have:

  • func: Used to create functions in Go language.
  • main. main: Is a function main. main in the Go language, contains no parameters, does not return any value, and is called when you execute the program.
  • Println(): This method is included in the package fmt 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 programs

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

$ go run first.go

The Hello World program is run using Golang

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments