Declaration difference

Hey there,
what is the difference between:

 var ctx context.Context
      ctx = context.Background()


ctx := context.Background()

Thank you :slight_smile:

1 Like

The second example just do not have declaration “var” the name is “Short variable declarations”

more examples:


more links:

1 Like

Thanks :slight_smile:

Adding to what @luk4z7 said,

you typically want to do the first way of declaration outside of a function/method. Short variable declaration was built for use inside a function, that way you don’t have to write var and enables us to use flexibility of dynamic typing languages.

Note that the first syntax isn’t just a declaration syntax, it’s combining a couple different syntaxes that appear similar to something you might see in c/c++. The first syntax is equivalent to:

var ctx context.Context
ctx = context.Background()

The brackets aren’t part of the declaration of ctx, it’s an anonymous code block. This declares the variable verbosely, then assigns it. This is in contrast to your second declaration that declares the type and assigns the value of the variable in the same statement (where the type is inferred from the return value of the Background() function).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.