我是Go的新手,我很困惑於範圍(如others)。下面使用條件語句(if)進行範圍問題
的代碼生成:
./excel.go:24: err declared and not used
./excel.go:25: sheet declared and not used
爲什麼會出現這種情況?我已經在父範圍中聲明瞭err
和sheet
,不是嗎?
Excel.go:
package main
import (
"os"
"fmt"
"github.com/tealeg/xlsx"
)
func main() {
var file *xlsx.File
var sheet *xlsx.Sheet
var row *xlsx.Row
var cell *xlsx.Cell
var err error
fileName := "MyXLSXFile.xlsx"
if _, err := os.Stat(fileName); os.IsNotExist(err) {
fmt.Printf("File does not exist so create one");
file = xlsx.NewFile()
sheet, err = file.AddSheet("Sheet1")
} else {
fmt.Printf("File exists so open");
file, err := xlsx.OpenFile(fileName) // <-- line 24
sheet := file.Sheets[0] // <-- line 25
}
row = sheet.AddRow()
cell = row.AddCell()
cell.Value = "I am a cell!"
cell = row.AddCell()
cell.Value = "I am another cell!"
err = file.Save(fileName)
if err != nil {
fmt.Printf("help")
}
}
啊哈,謝謝,這是完全合理的。 –