Golang syntax and functionalities

In go our first statement is package main, which means we are importing package main. Then second statement is import “fmt”, here also we are importing fmt package. Then why can’t we write import “main”, “fmt”. What is the difference?

Hi @anantsavvy,
We are not importing package main. We are declaring a package name called “main” and this will make our program executable.
About import keyword, we are importing other packages inside our code to use it’s functions like Printf(), Sprintf() and Println() functions and so on…

Thanks Tej. But when you say declaring package main, do you mean am creating it? No, I guess. Its something already existing and we are somehow telling the compiler to use this, right? So, still this is not clear for me. At best Google should have made the declaration default or inherent to any go program.

Hi @anantsavvy

Let me see if I can help to clear this up.

Declaration and import are not specific to golang - many languages have this concept. For example in Python we refer to module rather than package (although they mean much the same thing), There we would declare a module as a directory containing python files and the special file __init__.py, and import in other code with the import keyword

In golang, we are declaring a package with the package keyword, and that says that the rest of the code in this file is part of the package we declared, e.g. main. In golang, the main package has special meaning - it marks where the program begins when you run it.

With import, you bring in additional functionality your package needs which can be other packages written by you and part of the same overall program (it is good practice to break up a large program into smaller task-orientated packages), or third party packages providing specific functionality like YAML parsing, or as @Tej-Singh-Rana has said, the methods for printing text to the console (these written by the Go maintainers).

1 Like