LoginSignup
daisei-yoshino
@daisei-yoshino

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

golang - 複数返り値関数の結果+αを直接関数に与えたい

解決したいこと

複数のプリミティブ型から構成可能な構造に対し、単項演算・二項演算の関数を実装しました。
それを基に作成したいコードでは、数億回規模の演算を行うことになりそうだったので、構造体の生成や読み込みに掛かる時間を排除できればと思ったのと、wasmへのコンパイル時に軽量化できる可能性があるのとで、構造を成す変数をそのまま関数に与えるような形式でコーディングを試みました。
そのようにしたところ、二項演算(単項演算(変数列), 単項演算(変数列))等でエラーが発生しました。
できれば二項演算に直接単項演算等の結果を突っ込めれば有り難いというのと、単純にこの問題を回避する方法が気になるということで、質問させて頂きます。

発生している問題・エラー

sample.go
package multiRetFuncTest

func applyMatrix(x, y float32) (float32, float32) {
	return 2 * x, x - y
}

func addVec(x1, y1, x2, y2 float32) (float32, float32) {
	return x1 + x2, y1 + y2
}

func main() {
	vx, vy := addVec(1, 2, applyMatrix(3, 4)) // error
}

自分で試したこと

構造体を使う

単項演算・二項演算の返り値が1つになるので話が単純になります。
ただ、構造体の生成・読み出し・破棄に掛かる計算量が割と気になります……

一時変数に書き込んでそれを使う

代入され使用される変数全てがプリミティブ型となるので、上記問題は解決されます。
ただ、問題として、演算が入れ子になるような状況だと、変数を多数生成することになり、混乱しそうです……

0

1Answer

複値でも出来るけど他のパラメータは入れられないようですよ。

As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order. The call of f must contain no parameters other than the call of g, and g must have at least one return value. If f has a final ... parameter, it is assigned the return values of g that remain after assignment of regular parameters.

1

Comments

  1. @daisei-yoshino

    Questioner

    なるほど、そうなのですね……!
    ありがとうございます!

Your answer might help someone💌