# How To Create Package in Go

For reusable purpose, package is a good start to manage your Go codes because we can import and use it to our program.

Lets create a simple main file to begin with

```go
package main

import "fmt"

func main() {
   fmt.Println("hello world!")
}
```

It's a simple `hello world` program that printed out `hello world` string when we run `go run main.go` .

Now lets initiate a package with creating the module first. Commonly it's using a git repository even we have no plan to push it to any repository out there. In this example I will use my own Github repository and use `mygopackage` as package name.

```bash
git mod init github.com/didikz/mygopackage
```

Then create a subdirectory, for example I use `models` and create a `user.go` inside of it. The structure should be looks like this

![go package structure](https://cdn.hashnode.com/res/hashnode/image/upload/v1703989598372/be1ca15a-3a42-462d-b4b0-25d481007b9a.png align="center")

Inside `user.go` I would simple create a struct and a receiver that could be imported later in the `main.go` . I also set package name following the current directory name as `models`

```go
package models

type User struct {
	Id        int
	FirstName string
	LastName  string
	Address   string
}

func (user *User) GetName() string {
	return user.FirstName + " " + user.LastName
}
```

Get back to `main.go` and now we can try to import the package and use the defined struct. Use the module name initiated before along with the package name.

```go
import "github.com/didikz/mygopackage/models"
```

Now to use the user model from the package we can write like this

```go
var user models.User
user.Id = 1
user.FirstName = "Didik"
user.LastName = "Tri Susanto"
user.Address = "Malang"

// or alternatively
user := models.User{Id: 1, FirstName: "Didik", LastName: "Tri Susanto", Address: "Malang"}

fmt.Println(user.GetName())
```

All set. Next, If we run `go run main.go` then it should printed out `Didik Tri Susanto`

Easy right?

The final `main.go` class now should be like this

```go
package main

import (
	"fmt"

	"github.com/didikz/mygopackage/models"
)

func main() {
	user := models.User{Id: 1, FirstName: "Didik", LastName: "Tri Susanto", Address: "Malang"}
	fmt.Println(user.GetName())
}
```

That's it and happy coding!
