LoginSignup
0
0

More than 1 year has passed since last update.

Golangで関数にメソッドを生やす

Last updated at Posted at 2022-08-31

ある日

関数の型をdefined typeで定義していたとき、ふと思いました。「Golangはdefined typeで型を定義して、その型にメソッドを定義できる。一方関数がファーストクラスオブジェクトな言語であり、関数の型もdefined typeで定義できる・・・、なら関数の型にもメソッドを定義できるのでは?」と :thinking:

試してみた

package main

import "fmt"

type F func() int

func (r F) Add(i int) F {
	return func() int {
		return r() + i
	}
}

func (r F) Inc() F {
	return r.Add(1)
}

func (r F) Calc() int {
	return r()
}

func main() {
	var f F = func() int { return 1 }
	fmt.Printf("%d\n", f.Add(2).Inc().Calc())
}

できました :congratulations:

利用してるライブラリはないだろうか?

net/httpで実際に使われていました!

net/http/server.go
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)
}

感想

1年近くGolangを書いていましたが、つい最近まで知りませんでした。ジェネリクスも導入された今、これがないと困る!というほどのものではないかも?しれませんが、これを覚えておけば役に立つ日がきっとくる!・・・かもしれません! :joy:

もしどなたかより良い例やこれぞまさに使い所!という例がありましたら教えてください。

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