duanluan2047 2017-11-17 03:52
浏览 30
已采纳

当隐式工作时,在Go var声明中显式提供类型失败

I am new to go and currently going through the go tool tour.

While on the Short variable declarations section, I modified the sample code to look like this?

package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    var c bool, python string = true, "test"

    fmt.Println(i, j, k, c, python)
}

However, then I run the above code, I get the error:

# command-line-arguments
./compile233.go:8:12: syntax error: unexpected comma at end of statement

However, if I remove the types from the var declaration like the following:

package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    var c, python = true, "test"

    fmt.Println(i, j, k, c, python)
}

It works.

I cannot figure out what is wrong with the first example, and the error seems a bit misleading to me. Could anyone explain what I did wrong and why I'm getting the error?

  • 写回答

1条回答 默认 最新

  • dongliao9233 2017-11-17 03:57
    关注

    The variable declaration statement is defined as

    VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
    VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
    

    which means that if you want to declare multiple variables with type specified explicitly in a single statement they all must have the same type. And that type must come after the identifier list.

    So

    var foo, bar bool // is valid
    var foo bool, bar bool // is not (only one type qualifier is allowed)
    

    Reference:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法