Goのインストールから開発環境構築、学習にコマンドラインアプリの作成

goの開発環境を作る

公式からpkgでインストール

公式に則ってインストーラーでインストールしました。
トップのmacOSのリンクからだとIntel用になってしまうようなので、apple siliconの場合はdownloadのmoreからarm64のインストーラーをダウンロードします。
armとamdとあるのでapple siliconかintelでインストールする環境にあわせます。

インストーラーでも削除する時は可能

pkgでインストールした場合でもアンインストール可能です。

go.dev

goは、homebrewからもインストールできます。
そちらのほうが都合よい場合はbrewで。

特にパスを通すなどは必要なし

pkgからのインストールですと、特に追加のパスの設定等はありませんでした。

GOROOTは、/usr/local/go
PATHも/usr/local/go/binで追加されていました。

GOPATHは/Users/username/goでフォルダが作成されました。

GOPATHは上書きもできるらしいですが、私は特に変更せずです。

goのREPL

goのREPLのgoreをインストールしてみました。

goのいろいろ!はgithubに公開されているらしいです。

github.com

インストールコマンド

go install github.com/x-motemen/gore/cmd/gore@latest

公式ページで確認してください。

goreは入れただけではパスが通っていないので、パスを通します。 Make sure $GOPATH/bin is in your $PATH. です。

export GOPATH=$(go env GOPATH)
export PATH=$PATH:$GOPATH/bin

コマンドラインツール作成の教材

spf13.com

スライドです。
コマンドラインツールのUX、設計の段階から説明がありますので理解が深まると思います。

上記のスライドを公開されている方がcobraの作者のようですので、教材もcobraを使ってTodoを作っていきます。
完成ソースもgithubで公開されています。たいへんありがたいです。

2017年の公開ですので、スライドのとおりにいかないところも少しあります。

cobraのインストールで少々つまづく。自分だけかもしれませんが。
cobra-cliのインストールも必要。
cobra初期化の前に、go mod initが必要。
初期化はcobra init→cobra-cli initに変更。
パッケージが変更で、io/ioutil→os
ホームディレクトリの取得方法が、外部パッケージではなく、os.UserHomeDir()で可能。

リスト表示を整形する手前まで進んだところで、上記ぐらいありました。

goの入門にもなるかなと思ったのですが、ポイントなんかも出てくるので、教材のTodoを作れても、理解は追いつかない気がしています。

おまけ

スライド、英語なので翻訳しながらだったのですが参考までに。
機械翻訳のまま!それも不完全!
数字はスライド番号です。

7
agenda
Introduction to UX guidelines for CLIs
Design our experience
Build application
CLI の UX ガイドラインの紹介
エクスペリエンスの設計
アプリケーションの構築


8
rules
This is an interactive workshop
your participation is needed
Will follow the 50% rule
これはインタラクティブなワークショップです
あなたの参加が必要です
50%ルールに従います


12
go env
GOPATH


16
GOPATH/binにパスを通す


19 20
go path and setup
You WILL store your code in a github user folder
$GOPATH/src/github.com/username/helloworld
I hated this
I was comfortable with  /code/dev/ or /projects
コードは github ユーザー フォルダに保存されます
$GOPATH/src/github.com/username/helloworld
これは嫌でした
/code/dev/ または /projects の方が快適でした

By Storing code on github, I was able to share my many problems
Going from I m working on this to lets collaborate
コードをgithubに保存することで、多くの問題を共有できました
「これに取り組んでいます」から「協力しましょう」へと移行しました


21
setup
The path really only matters if you are publishing this
Start off assuming everything will be published
パスが本当に重要なのは、これを公開する場合のみです
まずはすべてが公開されると仮定してください


22
get and install cobra
cobra go get 悩ましい


25-
UNIX PHILOSOPHY
Simple Clear Composable Extensible Modular Small


34-
WHAT ARE COMMANDS
WHAT ARE ARGS
FLAGS
verb adverb noun
動詞 副詞 名詞
adverb
How  In what way  When  Where  To what extent
verb preposition obj
動詞 前置詞 目的語


79
Consists of a preposition and its object
Acts as an adverb
Speaking at craftconf
前置詞とその目的語から成ります
副詞として機能します
craftconf で講演


83
Launch something
Do more than one thing
collection of commanda
何かを起動する
複数のことを実行する
コマンドのコレクション


86
CLI apps do multiple things
Apps are groups of commands
sub commands have flags and args
All rules still apply
CLI アプリは複数のことを行います
アプリはコマンドのグループです
サブコマンドにはフラグと引数があります
すべてのルールが引き続き適用されます


87
APP  CMD  FLAG  ARG
NOUN  VERB  ADVERB  OBJECT
brew fetch -v hugo

NOUN  VERB  OBJECT
brew install hugo


97
think of how you would use your app
Pretend your app was built
Use it as if it existed
Feel it out
アプリの使い方を考える
アプリが作られたと仮定する
アプリが存在するかのように使う
実際に使ってみる


99-
todo appの構想


135
cobra


138
cd project folder

go mod init をしてから
cobra-cli init 


141
go install


145
VScode


150
cmd/root.go


151
Unit of organization of code in go
Organized by forders
Go のコード編成単位
フォルダ別に編成


152
Notice package name
matches dir
パッケージ名が dir に一致することに注意してください


159
cd project folder
cobra-cli add add


163
cmd/add.go


166
Function is a type
First class citizen in Go
Can have multiple input values
関数は型です
Go の第一級オブジェクト
複数の入力値を持つことができます


170
array
An array is an ordered sequence of elements of a single type
Fixed length
Arrays are indexed starting from 0
配列は、単一の型の要素を順序付けて並べたものです
固定長
配列は 0 から始まるインデックスが付けられます


171
slice
Segment of an array
dynamic length
Can be used without thinking about array underneath
配列のセグメント
動的長さ
下にある配列を意識せずに使用できます


172
for x, y := range
Provides a way to iterate over an array, slice, string, map, or channel
Like foreach  or each in other languages
x is index/key, y is value
_ allows you to ignore naming variables
配列、スライス、文字列、マップ、またはチャネルを反復処理する方法を提供します
他の言語の foreach または each と同様
x はインデックス/キー、y は値
_ を使用すると、名前付け変数を無視できます


175
init()
Special function
Called after package variable declarations
Each package may have multiple init()
init() order un-guaranteed
特殊関数
パッケージ変数宣言後に呼び出されます
各パッケージには複数の init() がある場合があります
init() の順序は保証されません


179
main.go


180
main main main
Go programs are all about main
main.go (convention)
main package
main()
main.main aslled after all init() are run
Go プログラムは main が基本です
main.go (規則)
main パッケージ
main()
main.main はすべての init() が実行された後に実行されます


181
main.goにcmdをimport
func main(){
cmd.Execute()
}


182
cmd/root.go


186
:=
assignment operater
declares & assigns in one operation
代入演算子
1回の操作で宣言と代入を行います


188
error handling
Errrors are not exceptional, they are just values
No exceptions in go
Error should be handled when they occur
エラーは例外ではなく、単なる値です
Go には例外はありません
エラーは発生したときに処理する必要があります


193
todo/todo.go
package todo


196
todo.goのItemをexported


197
named types
Can be any known type (struct, string, int, slice, a new type you've declared, etc)
Methods can be declared on it
Not an alias - Explicit type
名前付き型
既知の型であれば何でも可 (構造体、文字列、整数、スライス、宣言した新しい型など)
メソッドを宣言可能
エイリアスではない - 明示的な型


199
cmd/add.go
todo/をimport
github.com/username/tri/todo


200
cmd/add.go
Itemから取得するコードを書く


202
constructors
Go does not have constructors
If construction is required (initialization prior to use,) use a factory
convention is to use new __()
... or new() when only one tyoe is exported in the package
コンストラクタ
Go にはコンストラクタがありません
コンストラクションが必要な場合 (使用前に初期化)、ファクトリを使用します
慣例的に new __() を使用します
... または、パッケージでエクスポートされるタイプが 1 つだけの場合は new() を使用します


203
composite literals
An expression that creates a new value each time it is evaluated
eg.. []todo.Item{}
複合リテラル
評価されるたびに新しい値を作成する式
例: []todo.Item{}

cmd/add.go


206
append
Append adds new values to a slice
Append will grow a slice as needed
追加
追加はスライスに新しい値を追加します
追加は必要に応じてスライスを拡張します


210
go install
tri add "one two" three
[{one two} {three}]


215
saving data


216 217
todo/todo.go
json


223
cmd/add.go


226
ファイルに書き込み


230
データ読み込み


231
todo/todo.go


240
読み込んでリスト表示


241
cobra-cli add list


242
cmd/list.go


247
cmd/add.go


250
home dirを取得する
https://github.com/mitchellh/go-homedir は使えない?


253
cmd/root.go


259
cmd/add.go

log.Printf("%v", err)
// fmt.Errorf("%v", err)
スライドはErrorfだったが、警告黄色メッセージがvscode上で出ていたので、ReadItems()のエラー処理で使っていたlog.Printfにした


263
項目を追加する Priorityを追加


266
todo/todo.go


270
cmd/add.go


276
Break out listRun


277
cmd/list.go