Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 関数を引数として渡す | 関数
Go入門

book関数を引数として渡す

メニューを表示するにはスワイプしてください

もう一つの便利な機能は、関数を他の関数の引数として渡すことができる点です。

参考までに、パラメータを持つ関数の基本的な構文は次のとおりです:

func myFunc(param1 datatype, param2 datatype, ...) optional_return_type {
      // Code
      // Optional return statement
}

関数にパラメータを渡す際のデータ型の指定には、次の構文を使用します:

func(datatype, datatype, …) return_datatype

func キーワードの後に、カンマで区切られたパラメータのデータ型を括弧内に記述します。さらに、必要に応じて期待される関数や関数群の戻り値のデータ型も指定します。

例を用いると、この概念がより分かりやすくなります:

index.go

index.go

copy
12345678910111213141516
package main import "fmt" func nTimes(n int, msg string) { for i := 0; i < n; i++ { fmt.Println(msg) } } func printFiveTimes(msg string, show func(int, string)) { show(5, "Hello World") } func main() { printFiveTimes("HelloWorld", nTimes) }

上記の例では、nTimesという関数をprintFiveTimes関数の引数として渡しています。show関数の定義におけるprintFiveTimesパラメータのデータ型はfunc(int, string)であり、これはnTimes関数、すなわちnTimes(n int, msg string)の定義に対応しています。

次に、戻り値を持つ関数の例を見てみましょう。

index.go

index.go

copy
1234567891011121314151617181920
package main import "fmt" // A factorial is the product of all the numbers from 1 up till n // For-example factorial of 5 is 1x2x3x4x5, which is 120 func factorial(n int) int { var result int = 1; for i := 2; i <= n; i++ { result *= i } return result } func eval(n int, oper func(int) int) int { return oper(n) } func main() { fmt.Println(eval(5, factorial)) }
question mark

次のプログラムの出力はどうなりますか:

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  6

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  6
some-alt