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{
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错