Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationEventAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at


package main

import (

func main() {
  lines := fromFile("hoge.txt")
  fmt.Printf("lines: %v\n", lines)

func fromFile(filePath string) []string {
  // ファイルを開く
  f, err := os.Open(filePath)
  if err != nil {
    fmt.Fprintf(os.Stderr, "File %s could not read: %v\n", filePath, err)

  // 関数return時に閉じる
  defer f.Close()

  // Scannerで読み込む
  // lines := []string{}
  lines := make([]string, 0, 100)  // ある程度行数が事前に見積もれるようであれば、makeで初期capacityを指定して予めメモリを確保しておくことが望ましい
  scanner := bufio.NewScanner(f)
  for scanner.Scan() {
    // appendで追加
    lines = append(lines, scanner.Text())
  if serr := scanner.Err(); serr != nil {
    fmt.Fprintf(os.Stderr, "File %s scan error: %v\n", filePath, err)

  return lines


  • 改行区切りのテキストデータの読み込みはbufio.Scannerが便利なので使うべし
    • "Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text."
  • 空要素のスライスを用意し、appendで読み込んだ行内容を順次追加する
  • ファイルのクローズは関数return時に(確実に)行いたいのでdeferで呼ぶ。関数が長くなってreturnが複数箇所に存在するような場合に有用
    • defer指定処理が実行されるのはreturn時のみで、os.Exit(1)した場合は実行 されない ので注意
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Help us understand the problem. What are the problem?