1

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 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using Ainar-G's version to save on typing. But i have tested with both answers. Thank you both for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.