본문 바로가기
Go

[Go] Package

by llHoYall 2021. 10. 16.

A package is a bundle of structures, constants, variables, functions, etc. with the same purpose.

Using Package

If you want to use packages, use import keyword.

import "fmt"

You can alias to package.

import htemplate "html/template"

You can import packages even not used.

import _ "math"

In this case, you don't use the package, but you can get the effects of initializing the package.

Go Module

The use of Go modules became the default from version 1.16 onwards.

Therefore, if you want to use Go, you need to run this command first.

$ go mod init [PACKAGE_NAME]

Finding Package

Go finds packages in the following order.

1. from Go installation path

2. from $GOPATH/pkg that contains downloaded external packages

3. from the current Go module

Create Own Package

Create a project folder and run the initial command.

The package name is the same as its folder name.

For instance, I'll create a calc package.

// calc/calc.go

// calculates two integer numbers
package calc

// adds two integer numbers, and return the summation.
func Adder(a, b int) int {
  return a + b
}

If you named constants, variables, and functions start with uppercase, it exports to outside.

If you don't want to export it, you need to start with lowercase.

And, all exported packages, constants, variables, and functions need to have a docstring.

 

Now, Use this package.

package main

import (  
  "fmt"
  "mypackage/calc"
)

func main() {
  fmt.Println(calc.Adder(2, 3)) // 5
}

Naming Convention

  • Use lowercase letters only for package names.
  • Use one word as possible. If you need more than two words, don't separate them.

Nested Packages

Packages with similar functions can be put together into one higher package.

This is an example.

\-- src
    \-- github.com
        \-- xxxx
            \-- bigpackage
                \-- smallpackage1
                    \-- smallpackage1.go
                \-- smallpackage2
                    \-- smallpackage2.go
                \-- bigpackage.go

Then, you can use these packages.

import (
  "github.com/xxxx/bigpackage"
  "github.com/xxxx/bigpackage/smallpackage1"
  "github.com/xxxx/bigpackage/smallpackage2"
)

Initializing Packages

When the package is imported, Go compiler initializes global variables and calls init() function.

init() function does not have parameters and return values.

Package Documentation

If you write comments in packages, it will be shown on the document tool of Go.

Check the commands.

2020/10/26 - [Go] - [Go] Basic

'Go' 카테고리의 다른 글

[Go] Method  (0) 2021.10.17
[Go] Slice  (0) 2021.10.16
[Go] Rune and String  (0) 2021.10.16
[Go] Pointer  (0) 2021.10.11
[Go] Structure  (0) 2021.10.11

댓글