Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const declaration with multiple return values

Tags:

go

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?

like image 455
enjoylife Avatar asked Dec 25 '22 13:12

enjoylife


1 Answers

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.

like image 82
nemo Avatar answered Jan 12 '23 23:01

nemo