3
2

More than 3 years have passed since last update.

即時関数 使用例 (Go言語で)

Posted at

はじめに

入門書で言語の基礎を学んでいる時に即時関数ってどんな時に使うのかピンと来なかったのですが、インターンで使う機会があったので残しておこうと思います。
実際はJavaScriptを書いている時に使ったのですが、慣れる為にGo言語で書き換えました。

変数の初期値を引数によって変える

変数を作って、if,switch等で分岐して作られている変数に代入は面倒だなぁ~って時に使いました。

main.go
package main

import "fmt"

func main() {
    country := "日本"
    greeting := (func(country string) string {
        switch country {
        case "日本":
            return "こんにちは"
        case "アメリカ":
            return "Hello"
        default:
            return "xxxxx"
        }
    })(country)

    fmt.Println(country)    // 日本
    fmt.Println(greeting)   // こんにちは
}

おわりに

変数の初期値を引数によって変えようって時の書き方ってこれ良いのでしょうか?即時関数を使っていい場面なのか?
初心者すぎる疑問ばかりです。もっとコードを書いていき最適を考えられるようになりたいです。

3
2
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
3
2