dongxinche1264 2016-01-21 16:39
浏览 903
已采纳

在Go中声明变量而不指定类型

In Go variable declarations are followed by the intended type, for example var x string = "I am a string", but I am using Atom text editor with the go-plus plugin and go-plus suggests that I "should omit type string from declaration of var x; it will be inferred from the right-hand side". So basically, the code still compiles without specifying x's type? So is it unnecessary to specify variable types in Go?

  • 写回答

1条回答 默认 最新

  • doudouwd2017 2016-01-21 16:45
    关注

    The important part is "will be inferred from the right-hand side" [of the assignment].

    You only need to specify a type when declaring but not assigning a variable, or if you want the type to be different than what's inferred. Otherwise, the variable's type will be the same as that of the right-hand side of the assignment.

    // s and t are strings
    s := "this is a string"
    // this form isn't needed inside a function body, but works the same.
    var t = "this is another string"
    
    // x is a *big.Int
    x := big.NewInt(0)
    
    // e is a nil error interface
    // we specify the type, because there's no assignment
    var e error
    
    // resp is an *http.Response, and err is an error
    resp, err := http.Get("http://example.com")
    

    Outside of a function body at the global scope, you can't use :=, but the same type inference still applies

    var s = "this is still a string"
    

    The last case is where you want the variable to have a different type than what's inferred.

    // we want x to be an uint64 even though the literal would be 
    // inferred as an int
    var x uint64 = 3
    // though we would do the same with a type conversion 
    x := uint64(3)
    
    // Taken from the http package, we want the DefaultTransport 
    // to be a RoundTripper interface that contains a Transport
    var DefaultTransport RoundTripper = &Transport{
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料