Custom package in go and importing it

go mod init {REMOTE}/{USERNAME}/hellogo

Where {REMOTE} is your preferred remote source provider (i.e. github.com) and {USERNAME} is your Git username. If you don't use a remote provider yet, just use example.com/username/hellogo

➜  /workspace 
.
├── hellogo
│   ├── go.mod
│   └── main.go
└── mystrings <--custom package
    ├── go.mod
    └── mystrings.go

Inside hellogo go.mod

module example.com/username/hellogo

go 1.22.1

replace example.com/username/mystrings v0.0.0 => ../mystrings

require (
    example.com/username/mystrings v0.0.0
)

cat mystrings/mystrings.go

package mystrings

func Reverse(s string) string {
  result := ""
  for _, v := range s {
    result = string(v) + result
  }
  return result
}

cat hellogo/main.go

package main

import "fmt"
import "example.com/ush/mystrings"

func main() {
fmt.Println(mystrings.Reverse("hello world"))
}

Be aware that using the "replace" keyword like we did in the last assignment isn't advised, but can be useful to get up and running quickly. The proper way to create and depend on modules is to publish them to a remote repository. When you do that, the "replace" keyword can be dropped from the go.mod:

BAD

This works for local-only development

module github.com/wagslane/hellogo

go 1.22.1

replace github.com/wagslane/mystrings v0.0.0 => ../mystrings

require (
    github.com/wagslane/mystrings v0.0.0
)

GOOD

This works if we publish our modules to a remote location like GitHub as we should.

module github.com/wagslane/hellogo

go 1.22.1

require (
    github.com/wagslane/mystrings v0.0.0
)