dongxu1875 2015-12-09 17:53
浏览 398
已采纳

在if / for循环外重用变量的golang问题

I am new to Go and have been working through different issues I am having with the code I am trying to write. One problem though has me scratching my head. I have been searching net but so far did not find a way to solve this.

As you will see in the below code, I am using flag to specify whether to create log file or not. The problem I am running into is that if I put w := bufio.NewWriter(f) inside the if loop then w is inaccessible from the following for loop. If I leave it outside of the if loop then buffio cannot access f.

I know I am missing something dead simple, but I am at a loss at this moment.

Does anyone have any suggestions?

package main

import (
    "bufio"
    "flag"
    "fmt"
    "os"
    "time"
    "path/filepath"
    "strconv"
)

var (
    logFile = flag.String("file", "yes", "Save output into file")
    t      = time.Now()
    dir, _ = filepath.Abs(filepath.Dir(os.Args[0]))
)

func main() {
    flag.Parse()

    name := dir + "/" + "output_" + strconv.FormatInt(t.Unix(), 10) + ".log"

    if *logFile == "yes" {
        f, err := os.Create(name)
        if err != nil {
            panic(err)
        }
        defer f.Close()
    }
    w := bufio.NewWriter(f)

    for _, v := range my_slice {
        switch {
        case *logFile == "yes":
            fmt.Fprintln(w, v)
        case *logFile != "yes":
            fmt.Println(v)
        }
    }
    w.Flush()
}
  • 写回答

1条回答 默认 最新

  • dongluobei9359 2015-12-09 17:59
    关注

    os.Stdout is an io.Writer too, so you can simplify your code to

    w := bufio.NewWriter(os.Stdout)
    if *logFile == "yes" {
        // ...
        w = bufio.NewWriter(f)
    }
    
    for _, v := range mySlice {
            fmt.Fprintln(w, v)
    }
    w.Flush()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集