Webエンジニアの備忘録

およそ自己の作業メモとして残しております。

Go言語を試してみる

PHPに飽きたので、Golangなどに手を出してみました。

インストール

Macで実行環境を構築するにはbrew installが簡単そうだったので、こちらを試しました。

$ $ brew install go
==> Downloading https://homebrew.bintray.com/bottles/go-1.5.2.el_capitan.bottle.tar.gz
######################################################################## 100.0%
==> Pouring go-1.5.2.el_capitan.bottle.tar.gz
==> Caveats
As of go 1.2, a valid GOPATH is required to use the `go get` command:
  https://golang.org/doc/code.html#GOPATH

You may wish to add the GOROOT-based install location to your PATH:
  export PATH=$PATH:/usr/local/opt/go/libexec/bin
==> Summary
🍺  /usr/local/Cellar/go/1.5.2: 5336 files, 273M
$ go
Go is a tool for managing Go source code.
 :

入りました。

パスを通す

~/.bashrcなどに追記しておきます。

# golang
export GOPATH=$HOME/.go
export PATH=$GOPATH/bin:$PATH

Hello World

公式のコードをローカルで動かしてみます。 https://golang.org/

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

func main() {
    fmt.Println("Hello, 世界")
}

そのまま実行とビルドしてからの実行をテスト

$ go run hello.go
Hello, 世界
$ go build hello.go
$ ./hello
Hello, 世界

自動整形を試してみる

スペースを詰めてみる

func main(){

↓fmtを実行

$ go fmt
hello.go

戻される。

func main() {

改行してみる

func main()
{

↓fmtを実行

$ go fmt
hello.go:8:1: expected declaration, found '{'
exit status 2
$ go build hello.go
hello.go:8:1: expected declaration, found '{'
exit status 2

ビルドすらできない。

このあたりがPHPと違って素直に嬉しい。 しっかり基礎を覚えて、きれいにコードを書いてみたい。

日本語訳のチュートリアルを見つけた。 http://go-tour-jp.appspot.com/welcome/1 とりあえず、ここを頑張ってみようと思う。