LoginSignup
2
2

More than 1 year has passed since last update.

Go言語 無名関数の書き方

Posted at

Go言語の無名関数の記事が少ないので、ここでいくつか例を上げたいと思います。

環境

go 1.18

例1 : 即時実行

input
package main

import "fmt"

func main() {

	// 無名関数
	func() {

		fmt.Println("Welcome! to Go Lang")
	}()

}
ouput
Welcome! to Go Lang

例2 : 変数に代入してから実行

Go言語では無名関数を変数に割り当てる事ができます。
無名関数を変数に割り当てると、その変数は関数型となり、関数をコールするようにその変数をコールする事ができます。

input
package main

import "fmt"

func main() {

	// 変数に無名関数を割り当て
	value := func() {
		fmt.Println("Welcome! to Go Lang")
	}
	value()

}
output
Welcome! to Go Lang

例3 : 無名関数に引数を渡す

無名関数に引数を渡す事もできます。

input
package main

import "fmt"

func main() {

	func(ele string) {
		fmt.Println(ele)
	}("Let's Go")

}
output
Let's Go

例4 : 任意の関数に無名関数を引数として渡す

input
package main

import "fmt"

// 無名関数を引数に渡す
func GFG(i func(p, q string) string) {
	fmt.Println(i("Go", "for"))
}

func main() {
	value := func(p, q string) string {
		return p + q + "Go"
	}
	GFG(value)
}
output
GoforGo

例5 : 無名関数を戻り値として返す

input
package main

import "fmt"

// 無名関数を返却
func GFG() func(i, j string) string {
	myf := func(i, j string) string {
		return i + j + "Golang"
	}
	return myf
}

func main() {
	value := GFG()
	fmt.Println(value("Welcome ", "to "))
}
output
Welcome to Golang
2
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
2
2