The Go Language (PART-3)


In The Go Language (PART-2), we wrote an introductory go Hello World program. And we talk about go run and go build commands.


package main

import "fmt"

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


Let's now talk about the program itself. Go code is organized into packages, which are similar to libraries or modules in other languages. A package consists of one or more .go source files in a single directory that defines what the package does. Each source file begins with a package declaration, here package main, that states which package the file belongs to, followed by a list of other packages that it imports, and then the declarations of the program that are stored in that file.


For instance, the fmt package contains functions for printing formatted output and scanning input. Println is one of the basic output functions in fmt; it prints one or more values, separated by spaces, with a newline character at the end so that the values appear as a single line of output.


Package main is special. It defines a standalone executable program, not a library. Within package main the function main is also special—it’s where execution of the program begins. Whatever main does is what the program does. Of course, main will normally call upon functions in other packages to do much of the work, such as the function fmt.Println.

We must tell the compiler what packages are needed by this source file; that’s the role of the import declaration.


You must import exactly the packages you need. A program will not compile if there are missing imports or if there are unnecessary ones. This strict requirement prevents references to unused packages from accumulating as programs evolve.


Go does not require semicolons at the ends of statements or declarations, except where two or more appear on the same line.

Go takes a strong stance on code formatting. The gofmt tool rewrites code into the standard format, and the go tool’s fmt subcommand applies gofmt to all the files in the specified package, or the ones in the current directory by default. Many text editors can be configured to run gofmt each time you save a file, so that your source code is always properly formatted.


15 views0 comments

Recent Posts

See All