This is the second part of Go Zero, mainly about Go naming conventions, variables and constants.

Naming conventions

In Go, any identifier (variable, constant, function, custom type, etc.) should comply with the following rules:

  • A sequence of characters or numbers.
  • Starts with a character or underscore.
  • Cannot conflict with the Go keyword.

The keyword

The Go language has a total of 25 keywords. As follows:

break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var
Copy the code

So let’s take a look at which names are legal based on these points

foo  # legal
foo1 # legal
_foo # legalvariableIt is not recommended to use Chinese names

1foo # illegal
1 # illegal
type # illegal
a+b # illegal
Copy the code

variable

In the Go language, the common form for declaring variables is to use the VAR keyword: var Identifier Type. Such as:

var a int 
var b bool
var str string
Copy the code

We can also declare:

var (
    a int
    b bool
    str string
)
Copy the code

This factorization keyword is used to declare global variables.

When a variable is declared, it is automatically given a zero value of that type: int 0, float 0.0, bool false, string empty string, and pointer nil. Remember, all internals are initialized in Go.

Of course, declarations and assignment (initialization) statements can also be combined. Such as:

var a int = 15
var i = 5
var b bool = false
var str string = "Go says hello to the world!"


var (
    a = 15
    b = false
    str = "Go says hello to the world!"
    numShips = 50
    city string
)
Copy the code

At this point, we can omit the type of the variable because the Go compiler can automatically infer its type from its value.

Short statement

If a variable has an initial value, we can use a short declaration like := :

A := 1 // Declare a as an integer of 1Copy the code

This method can only be used in functions and will cause errors when used in global variable declarations.

constant

Constants are used to store data that does not change. It is defined in a similar way to variables. Constants are defined using the const keyword: const identifier [type] = value. Constants are defined according to the following rules:

  • A value must be assigned when declared.
  • Data types stored in constants can only be Boolean, numeric (integer, floating point, and complex), and string.
  • Cannot be declared with :=.

Such as:

Const a = 64 const (b = 4 c = 0.1) Monday, Tuesday, Wednesday, Thursday, Friday, Saturday = 1, 2, 3, 4, 5, 6 const ( Monday, Tuesday, Wednesday = 1, 2, 3 Thursday, Friday, Saturday = 4, 5, 6 )Copy the code

Afterword.

I am just a beginner of Go language, this article may have mistakes, welcome everyone to comment area exchange.