Follow the old cat to do GO basic grammar

In the last blog, the old cat has synchronized with everyone how to build the relevant GO language development environment. I believe all the little partners in the car should have finished the environment. At the beginning of this article, we will be familiar with the basic grammar of GO language. After this article is finished, we actually expect you to be able to write some simple code fragments like the old cat.

Variable definition

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

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

You can easily find that the definition of go language is special, and its variable name is placed before the type. In fact, I think this is also related to people's way of thinking. When writing variables, some people think of names first and then types, while some people think of types first and then names. It should be noted here that if we do not give the relevant initial value, the go language will actually bring its own initialization value. After the above program is executed through the main function, it will be output

0 ""

You can try to write it and then run it. As for the placeholder and why it is written, you can refer to the relevant manuals. These belong to dead knowledge.

Let's look at the following definitions. When assigning values to multiple variables at the same time, it can be written like this

func variableInitialValue(){
    var a,b int = 3,4
    var s string = "abc"
    fmt.Println(a,b,s)
}

Evolution is more complicated. In fact, you can directly not write the name of variables. Different types of variables can be written on the same line. GO language will automatically identify the type of variables.

func variableDeduction(){
    var a,b,c,d = 3,4,"666",true
    fmt.Println(a,b,c,d)
}

In GO syntax, we don't even write var, but directly initialize variables by: = as follows.

func variableShorter(){
    a,b,c,d := 3,4,"666",true
    fmt.Println(a,b,c,d)
}

However, this writing method can only be written in the method body. If there are variables acting in the package, it cannot be written at this time. It must be honestly in the form of VaR keyword or var keyword plus parentheses. The code is as follows:

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

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

However, there is a point to note in the above definitions. In any case, the defined variables must be used in the follow-up, otherwise syntax errors will be reported.

The above is the definition of almost all GO variables. Let's make a summary. Use the var keyword to define variables

  • Variable definition var a,b,c bool
  • Variable initialization var a,b string = "hello","world"
  • Variables can be defined in functions or packages
  • Of course, it is also used to define variables in var() set.
  • The compiler can automatically determine the type var a,b,c,d = 3,4,"666",true
  • Tags can be used to define variables in a function. A, B, C, D: = 3,4, "666", true. However, they cannot be used in the package and can only be used in the function

Basic data type

We introduced the definition of variables above, but what are the built-in variable types of our variables? At present, it is mainly divided into the following categories.

We mainly look at the relevant explanations in the figure above. As for the more detailed parts, we can slowly experience them in the process of subsequent use.

Constants and enumerations

The definition of variables introduced above is mainly defined by var keyword. In fact, the definition of our constants is similar to that of variables. Our constants are mainly defined by const. Let's take an example:

func constDefinition(){
    const name  string = "abc" //Type mode
    const name2 = "abc" //Ways to omit types
    const name3,age  = "abc",19 //Define multiple variables at the same time
    const (
        name4 = "abc"
        nickname = "bcd"
        age2 = 23
    ) //Set defined together
}

Next, let's look at enumeration types. In GO language, enumeration type is actually a special set of constants. Unlike the special enum keyword in java, let's take a look at the specific DEMO:

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

You can use it in this way. Of course, there is a relatively simple way to write it, as follows

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

If the keyword "iota" is used, the following value is a self increasing value. 0,1,2,3 respectively. Then the conversion of relevant storage size is as follows

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

You might as well try it.

Above, we have shared the definitions of all variables and constants with you. You can write them manually following the above demo. Next, we begin to enter the syntax of program control process.

Conditional statement

if conditional statement

Because it is relatively simple, and this familiarity with grammar is actually a process of memory, and 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
    }
}

What I want to explain is that there is no need for parentheses in the condition of if.

We use this conditional statement to write a small DEMO, which mainly reads the content from the file.

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

In this way, you can read the contents of the file abc.txt. Of course, you'd better try. You still have to do more on your own to master grammar. Let's look at another more coquettish way. We can even write the process directly into our If condition. The details are as follows:

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

There are two points on it.

  • The condition of if can be assigned
  • The scope of the variable assigned in the if condition is in this if statement

switch conditional statement

Similarly, let's look at the code directly.

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
}

You will find that there is no break statement in the statement I wrote above. In fact, the go language is quite human. I'm afraid that each statement will write a break, so the go switch will automatically break unless fallthrough is used. You can have some questions about panic. In fact, this is an error throwing behavior, similar to throw Exception in java. Here, our conditional statements are synchronized with you. It's very simple, but we need to practice.

Circular statement

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 another example, omitting 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, omitting the beginning, we read the information in a text line by line and print it out. Here, it is also equivalent to while
func printFile(fileName string)  {
    file,err := os.Open(fileName)
    if err !=nil {
        panic(err)
    }
    scanner := bufio.NewScanner(file)
    for scanner.Scan(){
        fmt.Println(scanner.Text())
    }
}
//We can even write it as an endless loop, which is equivalent to while
for {
    fmt.Println("abc")
}

There are two points to note:

  • You don't need parentheses in the condition of for
  • The initial condition, end condition and incremental expression can be omitted from the condition of for

Write at the end

After learning the above basic grammar, in fact, we can write some slightly more complex code fragments. The above example can also be written by interested partners. In fact, there is no good way to learn a programming language. The most important thing is that you have to do more to get familiar with it. I am a cat, more content. Welcome to search for official account of cat.

Keywords: Go

Added by ProblemHelpPlease on Fri, 19 Nov 2021 19:37:10 +0200