LoginSignup
2
2

More than 5 years have passed since last update.

Goで配列に対してビットワイズに任意の関数を適用する関数

Posted at

配列の要素それぞれに対してある処理をしたい時があります。Pythonなら+演算子でいけますがGoの場合は型が違うエラーが出ます。

package main

import "fmt"

func main() {
    v := []float64{1,1,1,1}
    fmt.Println(v+1)
}

prog.go:7: invalid operation: v + 1 (mismatched types []float64 and int)

そこで任意の型、任意の数の引数を持つ関数を配列の要素それぞれに適用する関数を考えました。

func BroadcastFunc(v []float64, f func(float64, ...interface{}) float64, args ...interface{}){
    for i,_ := range v{
        v[i] = f(v[i], args...)
    }
}

実行例
https://play.golang.org/p/MvuCcmXvkC

メリットを考えてみましたが、for文を書かなくていいのでネストが浅くなるぐらいですかね。。。

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