Basic Modules in Go

Create the module

When creating a new project do:

go mod init github.com/adilkhan/hacky

This will create the go.mod file with content similart to:

module github.com/adilkhn/hacky

go 1.13

Now if we need to add some module forexample the pq module to work with the postgresql data base we can install it :

go get github.com/lib/pq

The go.mod file now adds it to its list of requirements:

module github.com/adilkhn/hacky

go 1.13

require github.com/lib/pq

Our main file

package main
import "fmt"

func main() {
  fmt.Prinln("hello")
}

Create a package

  mkdir my_math
  cd  my_math
  touch arthimetic.go

the contents of the file will be:

package my_math

//Func name is capitalized since its an Exported func
func AddTwoNums(x int, y int) {
  return x + y
}

Now we can use this module from our main

package main
import (
  "fmt"
  "github.com/adilkhn/hacky/my_math"
  )

func main() {
  fmt.Println(my_math.AddTwoNums(1 + 3 ))
}
go run hacky.go

Output: 4

We see here how to create a go module. And then add our own modules to it.


go

167 Words

2019-09-03 14:26 -0400

comments powered by Disqus