在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()
}

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()