LoginSignup
22
17

More than 5 years have passed since last update.

vscodeに登録しているgoスニペット

Last updated at Posted at 2018-12-05

aptpod Advent Calendar 2018 6日目の記事です。
せっかく5日目まで続いているので書くことにしました。
今日決めたので小ネタで申し訳ないです。

対象

  • vscodeでgo書いてる人でスニペットの存在をしらない人
  • そもそもvscodeのスニペット機能知らない人
  • これからvscodeで何かプログラミング言語やりはじめるよーな人

本題

vscodeにはユーザスニペットの機能があります

スクリーンショット 2018-12-05 21.01.44.png

例えば、goであればgo.jsonのようなファイルが用意されています

スクリーンショット 2018-12-05 21.01.54.png

ここに自分がショートカットで呼び出したいコードとそれに対応するキー入力を書いておけば下記のように
スムーズにコードが書けるようになります。(気持ちいい)

ctx.gif

上記は、go使いなら誰しも一回は書くであろうcontextのスニペットです。
こんな風にgo.jsonに書いてあげます。

go.json
{
    "context": {
        "prefix": "ctx",
        "body": [
        "ctx, cancel := context.WithCancel(context.Background())"
        ]
    }
}

その他便利なショートカット

デバッグ

一番良く使ってます。。

fff.gif

go.json
{
    "Print to console": {
    "prefix": "fff",
        "body": [
            "fmt.Printf(\"%#v\\n\", $1)"
        ],
        "description": "Log output to console"
    },
}

エラー系

主題は別だけどmattnさんのブログで見かけて即登録

ie.gif

go.json
{
    "iferr": {
        "prefix": "ie",
        "body": [
            "if err != nil {",
            "\t$1",
            "}"
        ]
    },
}

その他

deferも書くのめんどいのでこう

go.json
{
    "defer func": {
        "prefix": "df",
        "body": [
            "defer func(){ $1 }()"
        ]
    },
}

tickerも地味に忘れるのでこう

go.json
{
    "ticker": {
        "prefix": "tic",
        "body": [
            "ticker := time.NewTicker($1 * time.Second)"
        ]
    },
}

さらにselect tickerしたければそれも登録(やりすぎかもしれません)

go.json
{
    "for select tic": {
        "prefix": "fst",
        "body": [
            "ticker := time.NewTicker($1 * time.Second)",
            "for {",
            "\tselect {",
            "\t\tcase :",
            "\t\tcase <-ticker.C:",
            "\t}",
            "}"
        ]
    },
}

余談ですが仕事柄、bitも確認したいときもあるのでこんなのも登録してます

go.json
{
    "1byte_bit": {
        "prefix": "1b",
        "body": [
            "fmt.Printf(\"%08b\\n\", $0)"
        ]
    },
    "2byte_bit": {
        "prefix": "2b",
        "body": [
            "fmt.Printf(\"%16b\\n\", $0)"
        ]
    },
}

sample

t.go
package main

import (
    "fmt"
)

func main() {
    fmt.Printf("%08b\n", 255)
    // 11111111
}

さいごに

スニペットによく使うものはとりあえず書いておくと、いちいちググらずに済んで楽ですし
自分のメモとして残しとくといいかも知れません。

僕のリポジトリに他に登録しているスニペットは貼ってあります。
https://github.com/smith-30/vscode-go-snippet

こんなのも便利というのあれば、MRなりこの記事のコメントに書いてくださると嬉しいです。

22
17
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
22
17