Skip to the content.

Your first project

In this chapter, we will cover how to create your first project in Go.

Introduction

This chapter will cover:

Module use cases

There are two interesting use cases with modules:

Consume internal files

You want to split up your app in many different files. Let’s say you have the following files:

/app
  main.go
  /helper
    helper.go 

What you are saying above is that your program consists of many files and that you want code in the fiile main.go to use code from helper.go for example.

To handle such a case, you need the following:

You can use go mod init, this will initialize your project.

Creating a project

To create a project, you run go mod init and a name for a project, for example, “my-project”:

   go mod init my-project

You end up with a go.mod file looking something like so:

   module my-project

   go 1.16

The go.mod file tells you the name of your project and the currently used version of Go. It can contain other things as well like libraries you are dependent on.

The import statement

Imagine now we have this file structure in our project:

/app
  main.go
  /helper
    helper.go 

with helper.go looking like so:

package helper
    
import "fmt"

func Help() {
  fmt.Println("This is a helper function")
}

to use the public Helper() function from main.go, we need to import it.

In main.go we need an import statement like so:

import (
  "my-project/helper"
)

We are now able to invoke the Help() function from main.go like so:

helper.Help()

Assignment - create a project

In this assignment, you will create a project.

  1. Create a project like so:

     go mod init my-project
    
  2. create the helper directory and helper.go file and give it the following content:

     // helper.go
        
     package helper
        
     import "fmt"
        
     func Help() {
      fmt.Println("This is a helper function")
     }
    
  3. Create the main.go file and give it the following content:

    package main
    
    import (
      "my-project/helper"
    )
        
    func main() {
      helper.Help()
    }
    

    Note this import "my-project/helper", it ensures the helper package is in scope.

  4. Compile and run

    go run main.go
    

Solution

helper/helper.go

package helper

import "fmt"

func Help() {
 fmt.Println("help")
}

main.go

package main

import "my-project/helper"

func main() {
 helper.Help()
}

Challenge

See if you can create another function in helper.go, this time, make the function name lowercase, what happens if you try to import it?