Golang Get Started

スポンサーリンク

Set up

This is an example to set up golang environment with Mac

This includes

  • Install golang
  • Prepare GOPATH
  • Set up VS Code
  • Create first project
  • Hello world
  • Run program

Install

To start go programming, please install go at first

Just download from https://golang.org/dl/ (based on your platform) and install

Check

go version

Prepare GOPATH

GOPATH is go lang install root ,and helpful to set up

Also, project should be under this.

For Mac, you can add GOPATH to .zprofile (for zsh)

.zprofile

export GOPATH=$(go env GOPATH)

After this, you can use

cd ${GOPATH} to go root

Go Structure

O.K. If you go GOPATH, you can go go root. Under this, there are a lot of to tool and sources.

The directory structure like this

GOPATH
|- bin
|- pkg
|- src
    |- github.com
    |- golang.org
    |- gopkg.in

All source codes for go should be under src

Under src, there are repository name and prepare your repo under this.

Set up VS Code

For programming, it’s better to IDE in terms of code management.

VS Code is powerful IDE to manage go

Install go plugin and go tools

After install VS Code , we can install go tools

“Code” -> “Preference” -> “Extensions” and search by “go”

You can see

And, Press “Command” + Shift + p
to see search. Search by “go update”
You can see to module list

Check all and install

Create first project

Go go root and github.com/DJ110 <- DJ110 is my repository name

cd ${GOPATH}/src/github.com/DJ110
mkdir goref
go mod

Use go mod to initialize go modules

If you have errors like

go: modules disabled inside GOPATH/src by GO111MODULE=auto; see ‘go help modules’

Please try following

export GO111MODULE=on
go mod init

O.K. Project structure becomes like

GOPATH
|- src
   |- github.com
        |- DJ110
             |- goref
                  |- go.mod

First go program, hello world

Let’s create main.go under your project

main.go

package main

import "fmt"

func main() {
	fmt.Println("Hello Gophers!")
}

Run

go run main.go

Another way to run

 go run github.com/DJ110/gorefs

golang
スポンサーリンク
Professional Programmer2

コメント