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:

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

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用