LoginSignup
0
0

【Go言語】コマンド1つでGoのプロジェクトを作る

Last updated at Posted at 2023-12-23

前置き

Goのプログラムを動かすために必要な動作は以下の4つです。他の言語であればいろいろと省ける部分がありますがGoはこのように動作が多いです。

cdなどを加えると打ち込むコマンドの数はそこそこ多くなるので大変です。

  1. ディレクトリの作成
  2. go mod init
  3. main.goを作成
  4. main.goにpackageとmain関数を用意する

便利にする

これらを1つのコマンドで実行できるようにすると便利です。そこで以下のような関数を用意しましょう。

function gomake() {
  rand=go-test-$(openssl rand -hex 2)
  mkdir $rand
  cd $rand
  go mod init test
  touch main.go
  echo "package main

func main(){}
  " > main.go
  code .
}

これを.bashrc.zshrcなどに追記しておくと、gomakeというコマンドでGoのプロジェクトを作成できるようになります。

具体的にこの関数が行っていることを説明します。

まずはじめにランダムなディレクトリ名を作成します。これはGoのプロジェクトを作成するたびにディレクトリ名が被らないようにするためです。opensslコマンドを用いてランダムな文字列を生成しています。

rand=go-test-$(openssl rand -hex 2)
mkdir $rand
cd $rand

次に、この部分ではgo mod initコマンドを実行して初期化を行ったあと、main.goを作成し、そこにpackage mainmain関数を書き込んでいます。

go mod init test
  touch main.go
  echo "package main

func main(){}
  " > main.go

これはすぐに作業ができるようにVScodeエディタを開くコマンドです。コマンドがない人はVScodeのコマンドパレットからShell Command: Install 'code' command in PATHを実行すうことでcodeコマンドが使えるようになります。

code .

このようにすることで簡単にGoのプロジェクトを作成できるようになります。
スクリーンショット 2023-12-23 12.28.10.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0