0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

巨大なデータを取得する関数でデータを戻り値にする代わり

Last updated at Posted at 2020-05-21

sink って名前がわかりやすいなと思ったので忘れないようにメモ。

Goで巨大なデータを取得する処理の場合、配列に入れて返すのどうなんってなりがち。

func FetchTooBigData() ([]Datum, error) {
  var data []Datum
  ...
  data = append(data, Datum{...})
  ...
  return data
}

メモリに全部載せるの流石にキツイ。

受け取るための某を作って引数で渡してやるのが設計的に簡単で良さそう。

type DataSink interface {
  Add(Datum) error
}

func FetchTooBigData(sink DataSink) error {
  ...
  if err := sink.Add(Datum{...}); err != nil {
    return err
  }
  ...
}

もっとちゃんと作り込んで、他の言語でよく見るチェーンっぽい書き方をするなら

type EnumerableData interface {
  Next() bool
  Current() Datum
}

func FetchTooBigData() (EnumerableData, error) {
  ... // よしなに
}

data, err := FetchTooBigData()
if err != nil {
  panic(err)
}

for data.Next() {
  datum := data.Current()
  ...後続処理
}

みたいなコルーチンじみたアレを作るんだろうけど、流石に面倒くさい。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?