This article will learn the basic syntax of Go language, such as variables and constants, data types, operators, conditional statements, loop statements.

Variables and constants

Variables and constants are an integral part of a computer program. This section shows you how to declare and use variables and constants in the Go program, as well as how to declare and scope.

Variable declarations

In Go, variables can be declared in a variety of ways. As mentioned in the previous article, Go is a statically typed language, so variables must be declared with their types specified.

Example: Declare a variable of type string.

package main

import "fmt"

func main(a) {
	var s1 string = "Hello World"
	var s2 = "Hello World"
	var s3 string
	s3 = "Hello World"
	fmt.Println(s1, s2, s3)
}
Copy the code
  • Declare variables using the keyword var.

  • Do not declare a type if the variable type can be derived by value. S2 can be inferred from its value to be of type string.

  • Variables can be assigned after they are declared. Unassigned variables have a zero value for that type.

The type of a variable is important because it determines what value can be assigned to the variable. For example, you cannot assign an integer to a variable of type string. Assigning a mismatched value to a variable causes a compilation error.

Example: Assign a value of string to a variable of int.

package main

import "fmt"

func main(a) {
	var i int
	i = "Hello World"
	fmt.Println(i)
}
Copy the code

Compiling the file will result in a compilation error.

go build main.go 
# command-line-arguments
./main.go:7:4: cannot use "Hello World" (type untyped string) as type int in assignment
Copy the code

Multivariable declaration

Example: Declare multiple variables of the same type and assign values (explicitly specifying the type).

package main

import "fmt"

func main(a) {
	var s1, s2 string = "S1"."S2"
	fmt.Println(s1, s2)
}
Copy the code

Example: Declare multiple variables of different types and assign values (no explicit type can be specified).

package main

import "fmt"

func main(a) {
	var s1, i1= "S1".1
	fmt.Println(s1, i1)
}
Copy the code

Example: Declare multiple variables of different types (explicitly specifying the type).

package main

import "fmt"

func main(a) {
	var (
		s1 string
		i1 int
	)
	s1 = "Hello"
	i1 = 10
	fmt.Println(s1, i1)
}
Copy the code

A variable can be assigned again after it has been declared, but the same variable can only be declared once; otherwise, a compilation error will result.

Short variable declaration

When declaring variables in functions, you can do it more succinctly.

package main

import "fmt"

func main(a) {
	s1 := "Hello World"
	fmt.Println(s1)
}
Copy the code
  • := represents a short variable declaration, which may not use var and does not specify a type, but must be assigned.

  • You can only use short variable declarations in functions.

Variable declaration best practices

The Go language provides many ways to declare variables, and the following declarations are all legal.

var s string = "Hello"
var s1 = "Hello"
var s2 string
s2 = "Hello"
s3 := "Hello"
Copy the code

Which approach should you use?

The Go language has a limitation on this — you can only use short variable declarations inside functions, and you must use var declarations outside functions.

The conventions followed in the standard library are as follows: short variable declarations are used inside functions with initial values, var is used outside functions and types are omitted; Use var without an initial value and specify the type.

package main

import "fmt"

var s = "Hello World"

func main(a) {
	s1 := "Hello World"
	fmt.Println(s, s1)
}
Copy the code

Variables and zero values

In the Go language, if a variable is not initialized when it is declared, it is the default value, which is also called zero. In other languages, uninitialized values are null or undefined.

package main

import "fmt"

func main(a) {
	var s string
	var i int
	var b bool
	var f float32
	fmt.Printf("%v %v %v %v\n", s, i, b, f)
}
Copy the code

In the Go language, the variable is checked to see if it is empty and must be compared with a zero value of that type. For example, to check whether a variable of type string is empty, check with “”.

package main

import "fmt"

func main(a) {
	var s string
	if s == "" {
		fmt.Println("S empty")}}Copy the code

Variable scope

Scope refers to where a variable can be used, not where it is declared. Go uses block-based lexical scopes, which simply means {} produces a scope.

Go language scope rules are as follows:

  1. A pair of braces ({}) denotes a block that can be nested
  2. Variables declared within a block can be accessed within the block as well as its subblocks
  3. A child block can access variables of the parent block, but the parent block cannot access variables of the child block

Example: Scope of the Go language.

package main

import "fmt"

func main(a) {
	var s1 = "s1"
	{
		var s2 = "s2"
		// Can access s1,s2
		fmt.Println(s1, s2)
		{
			var s3 = "s3"
			// Can access s1,s2,s3
			fmt.Println(s1, s2, s3)
		}
	}
	// Can only access s1
	fmt.Println(s1)
}
Copy the code

In simple terms, variables outside the block can be accessed from within the block, but variables inside the block cannot be accessed from outside the block.

Declare constants

Constants are values that remain constant only throughout the program. Constants must be assigned at declaration time and cannot be changed after declaration.

The Go language uses the const keyword to declare constants.

package main

import "fmt"

const s = "Hello"

func main(a) {
	const s2 = "World"
	const s3,s4 = "Hello"."World"
	fmt.Println(s, s2)
}
Copy the code

Constants also support multiple declarations at a time, and the scope of constants is the same as that of variables.

The data type

The Go language provides a wealth of data types, divided by category into Boolean, numeric (integer, floating point, complex), string, and derived. The pie types include pointer type, array type, structure type, interface type, Channel type, function type, slice type and Map type.

Derived types are covered later.

Boolean type

Boolean values can only be true or false. Some languages allow the use of 1 and 0 for true and false, but Go does not.

The Boolean zero value is false.

package main

import "fmt"

func main(a) {
	var b bool
	if b {
		fmt.Println("B is true")}else {
		fmt.Println("B is false")}}Copy the code

numeric

Numeric types in Go include integers, floating-point numbers, and complex numbers.

integer

type The number of bytes The scope of
byte 1 0 ~ 28
uint8 1 0 ~ 28
int8 1 – 27 ~ 27-1
uint16 2 0 ~ 216
int16 2 – 215-215-1
uint32 4 0 ~ 232
int32 4 – 231-231-1
uint64 8 0 ~ 264
int64 8 263-263-1
int Platform dependent (32-bit or 64-bit)
uint Platform dependent (32-bit or 64-bit)

Floating point Numbers

type The number of bytes The scope of
float32 4 3.403 e38 ~ 3.403 e38
float64 8 1.798 e308 ~ 1.798 e308

The plural

slightly

String type

A string can be any sequence of characters, including numbers, letters, and symbols. The Go language uses Unicode to store strings and therefore supports all languages in the world.

Here are some examples of strings:

var s = "$% ^ & *"
var s2 = "1234"
var s3 = "Hello"
Copy the code

The operator

Operators are used to perform data and logical operations while the program is running. Operators supported by the Go language are:

  • Arithmetic operator

  • Logical operator

  • Relational operator

  • An operator

Arithmetic operator

Arithmetic operators are used to perform arithmetic operations on numeric types. The following table lists the arithmetic operators supported by the Go language.

The operator instructions
+ add
Subtracting the
* multiply
/ division
% Take more than
++ Since the increase
Since the reduction of
package main

import "fmt"

func main(a) {
	var (
		a = 10
		b = 20
	)
	fmt.Printf("a+b=%d\n", a+b)
	fmt.Printf("a-b=%d\n", a-b)
	fmt.Printf("a*b=%d\n", a*b)
	fmt.Printf("a/b=%d\n", a/b)
	fmt.Printf("a%%b=%d\n", a%b)
	a++
	fmt.Printf("a++=%d\n", a)
	a--
	fmt.Printf("a--=%d\n", a)
}
Copy the code

Unlike other languages, Go does not provide the ++a, –a operator, only a++, a–.

Relational operator

The relational operator is used to determine the relationship between two values. The following table lists the relational operators supported by the Go language.

The operator instructions
= = Determine whether two values are equal
! = Determine if two values are not equal
> Determines whether the value to the left of the operator is greater than the value to the right
< Determines whether the value to the left of the operator is less than the value to the right
> = Determines whether the value to the left of the operator is greater than or equal to the value to the right
< = Determines whether the value to the left of the operator is less than or equal to the value to the right
package main

import "fmt"

func main(a) {
	var (
		a = 10
		b = 20
	)
	if a == b {
		fmt.Println("a==b")}else {
		fmt.Println("a! =b")}if a < b {
		fmt.Println("a<b")}else {
		fmt.Println("a>=b")}if a <= b {
		fmt.Println("a<=b")}else {
		fmt.Println("a>b")}}Copy the code

Logical operator

Logical operators are used to make logical judgments about operands. The following table lists the logical operators supported by the Go language.

The operator instructions
&& Logic and. The result is true if both operands are true, false otherwise
|| The logical or. The result is true as long as one of the operands is true, false otherwise
! Logic. The result is false if the operand is true, true otherwise
package main

import "fmt"

func main(a) {
	var a, b = true.false
	if a && b {
		fmt.Println("Both a and B are true")}else {
		fmt.Println("At least one of a and b is false.")}if a || b {
		fmt.Println("At least one of a and b is true.")}else {
		fmt.Println("A and b are both false")}if! a { fmt.Println("A is false")}else {
		fmt.Println("A is true")}}Copy the code

An operator

Bitwise operators are used to perform binary operations on integers. The following table lists the bitwise operators supported by the Go language.

The operator instructions
& Bitwise and
| Bitwise or
^ The bitwise exclusive or
>> Moves to the right
<< Shift to the left
package main

import "fmt"

func main(a) {
	var (
		a = 1
		b = 2
	)
	fmt.Printf("a&b=%d\n", a&b)
	fmt.Printf("a|b=%d\n", a|b)
	fmt.Printf("a^b=%d\n", a^b)
	fmt.Printf("a>>1=%d\n", a>>1)
	fmt.Printf("a<<1=%d\n", a<<1)}Copy the code

Conditional statements

Conditional statements are an important part of computer programs and are supported by almost all programming languages. Simply put, a conditional statement checks whether a specified condition is met and performs the specified action when it is.

The following table lists the conditional statements supported by the Go language.

if Consists of a Boolean expression followed by one or more statements.
if… else if… else Consists of multiple Boolean expression branches and provides exception branches
switch Perform different actions based on different conditions and provide default actions

Example: Use of if.

package main

import "fmt"

func main(a) {
	var a = 10
	if a > 10 {
		fmt.Println("A greater than 10")}else if a == 10 {
		fmt.Println("A is equal to 10")}else {
		fmt.Println("A less than 10")}}Copy the code

Example: Switch usage.

package main

import "fmt"

func main(a) {
	var a = 10

	switch a {
	case 1:
		fmt.Println("A is equal to 1")
	case 2:
		fmt.Println("A is equal to 2")
	case 10:
		fmt.Println("A is equal to 3")
	default:
		fmt.Println(Default branch)}}Copy the code

Unlike other languages, the Case branch of Go does not require a break.

Looping statements

While other languages typically provide for, while, foreach and other keywords to implement loops, Go provides only the for keyword, but similar effects are achieved.

for

The for loop has a classic three-stage structure:

  1. Loop initialization

  2. Cycle termination condition

  3. Cyclic step conditions

package main

import "fmt"

func main(a) {
  for i := 0; i < 10; i++ {
		fmt.Println(i)
  }
}
Copy the code

while

The while loop specifies a loop termination condition. If the condition is not met, the loop continues to execute and moves closer to the termination condition. If the condition is met, the loop terminates. (Loops without termination conditions are called dead-loops.)

package main

import "fmt"

func main(a) {
  i := 0
  for i < 10 {
		fmt.Println(i)
    i++
  }
}
Copy the code

An infinite loop does not require a termination condition.

package main

import (
  "fmt"
  "time"
)

func main(a) {
  i := 0
  for {
    fmt.Println(i)
    i++
    time.Sleep(time.Second)
  }
}
Copy the code

foreach

Foreach loops are used to iterate over data structures such as lists and dictionaries.

package main

import "fmt"

func main(a) {
  list := []int{1.2.3.4.5}
  for index, value := range list {
		fmt.Println(index, value)
  }
}
Copy the code

continue

Continue is used to skip the current loop and continue with the next loop.

package main

import "fmt"

func main(a) {
  for i := 0; i < 5; i++ {
    if i == 1 {
      continue
    }
    fmt.Println(i)
  }
}
Copy the code

The program determines that I is 1 and skips and executes the next loop. The program output is as follows.

0, 2, 3, 4Copy the code

3.1.5 break

Break is used to break out of the loop, and subsequent loops are not executed.

package main

import "fmt"

func main(a) {
  for i := 0; i < 5; i++ {
    if i == 1 {
      break
    }
    fmt.Println(i)
  }
}
Copy the code

The program breaks out of the loop when it determines that I is 1. The program output is as follows.

0
Copy the code

summary

This paper introduces the basic syntax of Go language, including the use of variables and constants, basic data types, flow control and other knowledge. The next chapter covers the Go language’s data container types, including arrays, slicing, and maps.