Golang在if/for循环之外重复使用变量的问题

huangapple go评论80阅读模式
英文:

golang issue with reusing variable outside of if/for loops

问题

我刚刚阅读了你提供的代码,并理解你的问题。你遇到的问题是在代码中如何正确地使用bufioflag包来创建日志文件。你希望在指定条件下创建日志文件,并将输出写入该文件。

根据你的代码,我注意到你在if语句块内部创建了文件f,但是在if语句块之外的地方尝试访问它。这导致了w无法访问f的问题。为了解决这个问题,你可以在if语句块内部声明w变量,并将其作为条件分支之外的变量进行声明。这样,w将在整个main函数中都是可访问的。

下面是修改后的代码:

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"

	var w *bufio.Writer // 声明 w 变量

	if *logFile == "yes" {
		f, err := os.Create(name)
		if err != nil {
			panic(err)
		}
		defer f.Close()
		w = bufio.NewWriter(f) // 在 if 语句块内部初始化 w
	} else {
		w = bufio.NewWriter(os.Stdout) // 在 else 分支内部初始化 w
	}

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

这样修改后,你应该能够在满足条件时创建日志文件,并将输出写入该文件。如果条件不满足,则将输出打印到标准输出。希望这可以解决你的问题!如果还有其他疑问,请随时提问。

英文:

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

得分: 1

os.Stdout也是一个io.Writer,因此你可以简化你的代码如下:

w := bufio.NewWriter(os.Stdout)
if *logFile == "yes" {
    // ...
    w = bufio.NewWriter(f)
}

for _, v := range mySlice {
    fmt.Fprintln(w, v)
}
w.Flush()

这段代码的作用是将mySlice中的元素逐行写入到标准输出或者文件中(如果logFile为"yes")。bufio.NewWriter用于创建一个带缓冲的写入器,fmt.Fprintln用于将内容写入到写入器中,w.Flush()用于将缓冲区中的内容刷新到底层的io.Writer中。

英文:

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

huangapple
  • 本文由 发表于 2015年12月10日 01:53:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/34185677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定