LoginSignup
8
8

More than 5 years have passed since last update.

Golangのos.Openはfor文の中に書く場合、deferで閉じてははいけない

Last updated at Posted at 2016-07-10
package main

import (
    "os"
)

func main() {

    for i := 0; i < 67757; i++ {
        file, err := os.Open(".")
        if err != nil {
            panic(err)
        }
        defer file.Close()
    }
}

この様にある一定数を超えると

panic: open .: too many open files となります。
実行例 https://play.golang.org/p/FUxEJaRwO4
※PlayGroundの制限でメッセージは違います

解決案としては、1例として

for i := 0; i < 167757; i++ {   
       func() {
            file, err := os.Open(".")
            if err != nil {
                panic(err)
            }
            defer file.Close()
        }()
    }   

こういうふうに無名関数化すると、解決します。

原因は何かと言うと、defer が実行されるタイミングと、ファイルを開ける限界数です。

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

必要な部分を抽出して此処に書きましたが

どうでもいいこと含めた内容は別に書いてますー。

参考

8
8
2

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