猿问

如何检查字符串中的变量是否为空白

想要达到

我正在用 Go 构建一个应用程序。它是从 excel 文件创建一个 ruby 文件。


如果xx中有值,我想把它放在数据中,如果它是空白的,我想跳过这个过程。但是,如果我如下所示输入 nil,则会出现错误。


xx = xx + 19

if row[xx] ! = nil {

  data["IndustryId"] = row[xx];

  }

invalid operation: row[xx] != nil (mismatched types string and nil)

我希望你能帮助我。


代码

测试.go

func main() {

  excel_file, err := excelize.OpenFile("./excel/data.xlsx")

  if err != nil {

    fmt.Println(err)

    return

  }


  seeds := make([]string, 0, 1000)

  seeds = append(seeds, "# Seed")

  seeds = append(seeds, "# " + time.Now().Format("RFC3339"))

  seeds = append(seeds, "")


  tpl := template.Must(template.ParseFiles(`test.tmpl`))


  rows, err := excel_file.GetRows("Test")

  for i, row := range rows {

    if i != 0 {


      xx := 2

      data := map[string]string{

        "Id": row[xx],

      }



      xx = xx + 19

      if row[xx] != nil {

        data["IndustryId"] = row[xx];

      }


      if err := tpl.Execute(&output, data); err != nil {

        fmt.Println(err)

        return

      }


      seeds = append(seeds, output.String())

    }

  }


  export_file("./seeds/import_test.rb", seeds)

}


人到中年有点甜
浏览 125回答 2
2回答

明月笑刀无情

rows, err := excel_file.GetRows("Test")这rows是类型[][]string。现在当你这样做时:for i, row := range rows { ... }row是的[]string,现在如果你索引它,你会得到一个字符串。字符串的零值是""(空字符串) 而不是nil。因此,请将其与""而不是进行比较nil。这里:row[xx] != ""

波斯汪

您应该 Trim row[xx] 以确保该行不只包含空格并将其与“”而不是 nil 进行比较。import strings ....strings.TrimSpace(row[xx]) != "" 
随时随地看视频慕课网APP

相关分类

Go
我要回答