In the last blog, the old cat has synchronized with everyone how to build the relevant GO language development environment, I believe that the friends in the car should have already solved the environment. So let’s begin this article by familiarizing ourselves with the basic syntax of GO. With this done, I expect you to be able to write some relatively simple code snippets like the old cat.

Variable definitions

The definition of a variable is actually relatively simple, mainly using the var keyword + the name of the variable + the type of the variable. Examples are as follows:

func variableDefinition(a)  {
	var a int
	var s string
	fmt.Printf("%d %q\n",a,s)
}
Copy the code

You can easily see that the GO language is defined in such a way that variable names come before types. In fact, I think it is also related to the way people think. Some people think of the name first and then the type when writing variables, while some people think of the type first and then the name. It is important to note that if we do not assign an initial value, the go language will have its own initialization value, which will be printed after the above program is executed through the main function

0 ""
Copy the code

You can try to write it and run it, and you can look it up in the manual as to what the placeholders are and why they’re there. This is dead knowledge.

If multiple variables are assigned at the same time, we can write it this way

func variableInitialValue(a){
	var a,b int = 3.4
	var s string = "abc"
	fmt.Println(a,b,s)
}
Copy the code

You can write variables of different types on the same line, and GO automatically identifies the type of the variable.

func variableDeduction(a){
	var a,b,c,d = 3.4."666".true
	fmt.Println(a,b,c,d)
}
Copy the code

In GO syntax, we don’t even write var. We use: = to initialize variables.

func variableShorter(a){
	a,b,c,d := 3.4."666".true
	fmt.Println(a,b,c,d)
}
Copy the code

But this can only be done inside a method, if there is a variable in the package, then you can’t do this. You have to use the var keyword, or use the var keyword with parentheses. The code is as follows:

var (
	aa = 1
	bb = "ktdaddy"
	cc = true
)

func variableDefinition(a)  {
	var a int
	var s string
	fmt.Printf("%d %q\n",a,s)
}
Copy the code

However, there is a caveat to these definitions. No matter how you define them, the variables must be used later in the definition. Otherwise, syntax errors will be reported.

So that’s pretty much all of the variables of GO, so let’s summarize. Use the var keyword to define variables

  • The variables are defined var a,b,c bool
  • Var a,b string = “hello”,”world”
  • Variables can be defined within functions or packages
  • The var() set is also used for variable definition.
  • The compiler can automatically determine the type var a,b,c,d = 3,4,”666″,true
  • A,b,c,d := 3,4,”666″,true, but not in packages, only in functions

Basic data types

Above we have introduced the definition of a variable, but what are the built-in variable types of our variable? At present, it is mainly divided into the following categories.

Mainly look at the above related explanation, as for the more detailed place, we can slowly experience in the process of subsequent use.

Constants and enumerations

The way we define variables is by using the var keyword. In fact, the way we define constants is similar to the way we define variables. We define constants by using const. Let’s look at an example:

func constDefinition(a){
	const name  string = "abc" // Type mode
	const name2 = "abc" // Omit the type of way
	const name3,age  = "abc".19 // Define multiple variables simultaneously
	const (
		name4 = "abc"
		nickname = "bcd"
		age2 = 23
	) // set together
}
Copy the code

Next, let’s look at enumerated types. In the GO language, enumerated types are really a special set of constants. Unlike Java, which has a dedicated enum keyword, let’s look at a specific DEMO:

func enums(a){
	const (
		cpp = 0
		java = 1
		golang = 2
		python = 3
	)
	fmt.Println(cpp,java,java,golang,python)
}
Copy the code

It works like this, and of course there is a more concise way to write it, which is as follows

func enums(a){
	const (
		cpp = iota
		java 
		golang 
		python
	)
	fmt.Println(cpp,java,java,golang,python)
}
Copy the code

If the keyword “iota” is used, the following value is an incremented value. 0,1,2,3. Then the conversion of the relevant storage size is as follows

func storage(a){
	const (
		b = 1< < (10*iota)
		kb
		mb
		gb
		tb
		pb
	)
	fmt.Println(b,kb,mb,gb,tb,pb)
}
Copy the code

You might as well try it.

Above, we have shared the definitions of all variables and constants with you, you can follow the above demo to write their own, and then we start to enter the syntax of the program control flow.

Conditional statements

If conditional statement

Because it is relatively simple, and this kind of grammar familiarity is actually a memory process, there is no reason to say, so let’s go directly to the code.

func ifTest(v int)  int{
	if v<100 {
		return 50
	}else if v>100 && v<300{
		return 60
	}else{
		return 0}}Copy the code

The main thing I want to show you is that you don’t need parentheses in the if condition.

We use this conditional statement to write a small DEMO that reads mainly from a file.

func main(a) {
	const filename  = "abc.txt"
	contents,error := ioutil.ReadFile(filename)
	iferror ! =nil {
		fmt.Println(error)
	}else {
		fmt.Printf("%s\n",contents)
	}
}
Copy the code

In this way, you can read the contents of the file ABC. TXT, of course, we had better try, the grammar of things or have to do more to master. Now, another way to write it, which is a little bit more elegant, is we can even write the process directly into our If condition. Details are as follows:

func main(a) {
	const filename  = "abc.txt"
	ifcontents,error := ioutil.ReadFile(filename); error ! =nil{
		fmt.Println(error)
	}else {
		fmt.Printf("%s\n",contents)
	}
}
Copy the code

There are two points on it.

  • If conditions can be assigned
  • The scope of the variables assigned in the if condition is in the if statement

Switch conditional statement

Again, let’s just look at the code.

func switchTest(a,b int,op string) int{
	var result int
	switch op {
	case "+":
		result = a + b
	case "*":
		result = a * b
         fallthrough
	case "/":
		result = a / b
	case "-":
		result = a - b
	default:
		panic("unsupport operate" + op)
	}
	return result
}
Copy the code

You’ll notice that there is no break statement in the statement I wrote above. In fact, go language is still relatively human, afraid to write a break for each statement, so go switch will automatically break, unless fallthrough is used. If you have any doubts about panic, it is actually a throwing error, similar to a Java throw Exception. At this point, our conditional statement and you are done synchronization, very simple, but to practice.

Looping statements

For statement

Let’s look at the code directly, the specific DEMO is as follows:

sum :=0
for i:=1; i<100; i++{ sum +=i }// For example, to omit the beginning, we write an integer to binary
func convertToBin(n int)  string{
	result := ""
	for ; n>0 ; n /=2 {
		lsb :=n%2
		result = strconv.Itoa(lsb) + result
	}
	return result
}
// For another example, if we omit the start, we read the information in a text line by line and print it out, again equivalent to while
func printFile(fileName string)  {
	file,err := os.Open(fileName)
	iferr ! =nil {
		panic(err)
	}
	scanner := bufio.NewScanner(file)
	for scanner.Scan(){
		fmt.Println(scanner.Text())
	}
}
// We can even write it as an infinite loop, which is equivalent to while
for {
    fmt.Println("abc")}Copy the code

There are two points to note above:

  • I don’t need parentheses in my for condition
  • You can omit the initial condition, the end condition, the increment expression in the for condition

Write in the last

Once you’ve done the basic syntax, you can actually write some slightly more complex code snippets. The above example interested partners can also start to write, in fact, there is no good way to learn a programming language, the most important is to do a lot of work to be well familiar with. I am an old cat, more content, welcome you to search attention to the old cat public number “programmer old cat”.