
As we saw in the previous post regarding the definition of packages, this concept is very important in application design and as part of good practice. We also talk about the principle DRY - Don’t Repeat Yourself, but we will talk about this principle later.
Generally speaking, you must be able to reuse our packages but also those provided in the base library or any other third-party libraries.
package main import ( "fmt" ) func main() { fmt.Println("Hello, playground") }
In our example, we ask GO to import the _fmt_package, This package contains a set of functions related to display and formatting on the screen. Thanks to this package approach it will allow reuse in any other program, application or package. In addition, to access a function contained in this package, we will use point notation. We’ll prefix with the package name and then the dot and finish the function name in our case.
This import declaration allows the use of functions that are in packages outside our application directly within our source code.
import
There are several syntaxes for importing packages. See below for the different writes.
The scope of the import of a package is at the file level and not at the scope of the package. If it is used on several files, it should be imported into each GO file.
Presentation of the different entries to import packages into a program. The names of packages are always in quotation marks. For further clarification, I will refer you to the official documentation on language specifications here
package main import "fmt" func main() { fmt.Println("Foobar") }
package main import ( "fmt" "math" ) func main() { fmt.Println(math.Mod(7, 2)) }
package main import ( "fmt" myMathPackage "math" ) func main() { fmt.Println(myMathPackage.Mod(7, 2)) }
This notation is not recommended, even to be banned because it will rather bring confusion in the reading of the code.
package main
import ( . "fmt" . "math" ) func main() { Println(Mod(7, 2)) }
This will allow you to have the initializations that are, possibly, in the math package. All these initializations must be in the init function of the package. Not everything else will be accessible.
package main import ( "fmt" _ "math" ) func main() { fmt.Println("My name is John Doe") }
In some cases, packages or even yours may be subdivided into other sub-adjacent packages. So you have to be able to import them as well. Let’s take the case of the math_package, it is subdivided into 4 packages (so 4 subdirectories) which are: _rand, big, cmplx, bits and take for example the case where you want to work only with bits.
package main import ( "fmt" "math/bits" ) func main() { fmt.Printf("LeadingZeros16(%016b) = %d\n", 1, bits.LeadingZeros16(1)) }