# How to create a package in golang.

In golang we use a package using the import keyword.

For a single package:

```go
import "fmt"
```

For multiple packages, we use the multi line syntax:

```go
import (
	"fmt"
	"math"
	"log"
)
```

Similar to initializing multiple variables:

```go
var (
	a int
	b int
	c int
)
```

#### Ever wondered what the ```package main``` at the top of every go file means?

It's a package declaration, all go files must belong to a package.

The ```go run``` command can only execute go files in the main package.

Now that we know about packages lets move to creating our own package, we would be creating a __furthermaths__ package.

Don't worry your __furthermaths__ package would be easier than regular mathematics 🙂.


# Step 1: Create a project directory

e.g

```bash
mkdir $GOPATH/src/github.com/fuadop/furthermaths

cd $GOPATH/src/github.com/fuadop/furthermaths

go mod init
```

# Step 2: Create a go file

You can name it whatever you wish. I would go with ```math.go```.

```bash
touch math.go
```

# Step 3: Declare the package

Instead of adding ```package main``` to the top of the file, we would be adding our package name.
i.e
```go
package furthermaths
```

We would be defining only one function in our package, which is the ```Add``` function.

Before we continue, there is something you must know when defining functions in a custom package.

1. To make your function accessible outside the package, the function name must begin with an uppercase letter. The same is applicable to variables.

This is similar to private and public members of a class in OOP (Object Oriented Programming).

Now that you know that, let us go on with defining our ```Add``` function.

```go
package furthermaths

// Adds multiple amount of numbers
func Add(nums ...int) int {
	var result int
	for _, num := range nums {
		result += num
	}
	return result
}
```

We have finally created a __furthermaths__ package with an Add function.

To use this function in another project, you need to install the package using the ```go get``` command.

```bash
go get github.com/fuadop/furthermaths
```

The function can be used like so:

```go
package main

import (
	"fmt"

	"github.com/fuadop/furthermaths"
)

func main() {
	fmt.Println(furthermaths.Add(1, 2, 3, 4))
}
```

Running the above command would print 10 to the console.

```bash
10
```

To get the  package source code, [click here](https://github.com/fuadop/furthermaths).

