0
1

関数を引数として渡す方法(Go言語)

Posted at

Go言語では、関数を他の関数の引数として渡すことができます。これは高階関数(higher-order functions)と呼ばれ、関数型プログラミングの強力な機能の一つです。

基本的な使い方についての例

まず、関数を引数として渡す基本的な方法を見てみましょう。以下は、簡単な例です。

package main

import (
    "fmt"
)

// 関数型の定義
type operation func(int, int) int

// 関数を引数に取る関数
func compute(a int, b int, op operation) int {
    return op(a, b)
}

// 足し算の関数
func add(x int, y int) int {
    return x + y
}

// 引き算の関数
func subtract(x int, y int) int {
    return x - y
}

func main() {
    a, b := 5, 3

    // 足し算を実行
    sum := compute(a, b, add)
    fmt.Printf("足し算: %d + %d = %d\n", a, b, sum)

    // 引き算を実行
    diff := compute(a, b, subtract)
    fmt.Printf("引き算: %d - %d = %d\n", a, b, diff)
}

上記のコード:
https://go.dev/play/p/ztv71ZaA3RP

上記のれとして説明します。

関数型の定義

上記のコードでは、operationという関数型を定義しています。この型は、2つの整数を引数に取り、整数を返す関数を表します。

type operation func(int, int) int

関数を引数に取る関数

次に、computeという関数を定義しています。この関数は、2つの整数とoperation型の関数を引数に取り、その関数を実行して結果を返します。

func compute(a int, b int, op operation) int {
    return op(a, b)
}

操作を行う関数

addとsubtractは、それぞれ足し算と引き算を行う関数です。

func add(x int, y int) int {
    return x + y
}

func subtract(x int, y int) int {
    return x - y
}

まとめ

Go言語では、関数を引数として渡すことで、コードの柔軟性と再利用性を高めることができます。高階関数を使用することで、汎用的な操作を簡潔に記述することが可能です。ぜひ、実際のプロジェクトで試してみてください。

0
1
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
1