#02 The Basic Structure of the Go file

#02 The Basic Structure of the Go file

·

1 min read

Table of contents

No heading

No headings in the article.

A go file has the following parts:

  • Package declaration
  • Import packages
  • main() function

Example:

package main

import "fmt"

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

package keyword defines the package name because every program is a part of the package, In the above code, I set the package name as main which will indicate that this package belongs to the main package.

import "fmt" used to import package function. Multiple packages can be imported using import ().

Example:

import (
    "fmt"
    "time"
)

func main() {
    start := time.Now()
    t := time.Now()

    fmt.Println("Hello, 世界")
    elapsed := t.Sub(start)
    fmt.Printf("Time takes: %d\n", elapsed)
}

func main() {} is the entry point of Golang, According to Golang reference “The main package must have package name main and declare a function main that takes no arguments and returns no value.”

If I don’t write the main() function the code will not execute and return the output:

runtime.main_main·f: function main is undeclared in the main package.

fmt.Println("Hello World!") the “fmt” package is the standard library of Go, fmt package has I/O functions such as Printf(), Println(), Scanf() so on. To use print, scan and other I/O function fmt package will require.