dtz63853 2014-02-19 18:05
浏览 59
已采纳

具有多个返回值的const声明

I am wanting to define a constant value:

 const var *url.URL = url.Parse("http://yahoo.com/")

I know I have to fully define the variable and its type. ie I cant just use the ":=" shorthand.

But the return value from the evaluated function returns both the constant and a error.

  var, _ := url.Parse("http://yahoo.com/")

Now how do I declare that var is constant and discard the error in this case?

  • 写回答

2条回答 默认 最新

  • dongzong1866 2014-02-19 18:15
    关注

    First of all, you don't need to specify the type, you can simply write var foo = <expression>. The only reason why you need to use var instead of := is that short variable declarations are only allowed in functions but you're operating outside of functions.

    Secondly, you can't use function calls for constant values as these would not be constant (the function must be evaluated, that's against Go's definition of constant). See also the spec on what constants are:

    A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as unsafe.Sizeof applied to any value, cap or len applied to some expressions, real and imag applied to a complex constant and complex applied to numeric constants. The boolean truth values are represented by the predeclared constants true and false. The predeclared identifier iota denotes an integer constant.

    No user-defined functions here.

    What you can do is to define a var (on play):

    func MustParse(s string) url.URL {
        url, err := url.Parse(s)
        if err != nil { 
            panic(err); 
        }
        return *url
    }
    
    var foo = MustParse("http://yahoo.com/")
    

    Of course you could also do

    var foo, _ = url.Parse("foo")
    

    but with this you wouldn't see if your URL is wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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