如果/否则条件定义变量。未定义:dat(变量)

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

if/else condition defines variable. undefined: dat (variable)

问题

我知道这是一个基础问题,但我很好奇为什么下面的代码不起作用。在没有声明该变量的情况下,没有使用案例。

if (bundled == "true") {
    dat, err := Asset("index.html")
} else {
    dat, err := ioutil.ReadFile("./index.html")
}
if (err != nil) {
    os.Exit(0)
}

t, _ = t.Parse(string(dat))
p := Person{Scope: ""}
t.Execute(w, p)

我得到了错误信息

.\run.go:262: undefined: dat

我确定这只是我还在学习的基本 GOLANG 东西。

谢谢你的支持。

英文:

I know this is a basic question, but I'm curious why the code below does not work. There is no use case where this variable would not be declared.

if (bundled == "true") {
			dat, err := Asset("index.html")
		} else {
			dat, err := ioutil.ReadFile("./index.html")

		}
		if ( err != nil) {
			os.Exit(0)
		}

		t, _ = t.Parse(string(dat))
		p := Person{Scope: ""}
		t.Execute(w, p)

I get the error

.\run.go:262: undefined: dat

I'm sure it's just basic GOLANG stuff I'm still learning.

Thanks for your support

答案1

得分: 3

if-else代码块有自己的作用域。在你的情况下,dat在它们之外是不可见的。

你可以在if (bundled == "true")之前声明var dat []byte来修复它。

文档:https://golang.org/ref/spec#Declarations_and_scope

你可能还想阅读:Go中的声明作用域

英文:

if-else blocks have their own scope. In your case datis not visible outside of them.

You can declare var dat []byte before if (bundled == "true") to fix it.

Docs: https://golang.org/ref/spec#Declarations_and_scope

You may also want to read: Declaration scopes in Go

huangapple
  • 本文由 发表于 2017年2月7日 02:20:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/42074611.html
匿名

发表评论

匿名网友

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

确定