dongmozhui3805 2016-01-06 12:47
浏览 61
已采纳

带条件语句(if)问题的范围

I'm new to Go and I'm struggling with scope (as others).

The code below generates:

./excel.go:24: err declared and not used
./excel.go:25: sheet declared and not used

Why does this happen? I have declared both err and sheet in the parent scope, haven't I?

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")
    }
}
  • 写回答

2条回答 默认 最新

  • dongxingqiu7943 2016-01-06 12:50
    关注

    Use = instead of :=:

        file, err = xlsx.OpenFile(fileName) // <-- line 24
        sheet = file.Sheets[0] // <-- line 25
    

    Go allows re-declaring variables with the same name in nested blocks. := declares a new variable. In your case both err and sheet are declared inside else block but are not used there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?