Editor changed to GoLand, look at the source extremely convenient. Even the shortcut keys took a while to get used to. Today I started reading the Go Programming Language, also known as the Go Language Bible.

$ ./goBible --typeName =Go language Bible (一) -- Chapter =Program Structure
Copy the code

1. There are four ways to declare variables

Although Go has always said that it is very concise, removing a lot of redundant grammar. There are four different ways to declare a variable. Let’s say we want to declare a string variable called s:

  1. var s string
  2. var s = ""
  3. s := ""
  4. var s string = ""

Without going into the grammar, very basic things, here are the four ways to use each case:

  1. The first is obviously used when no initialization is required (or only zero values are required). (Again, there is no such thing as uninitialized in Go, everything is initialized.)
  2. 2 and 3 are actually completely interchangeable. But in general, 2 is more formal and is used to declare some package-level variables. 3 is generally used for some local variables in the function to save trouble.
  3. 4 might seem redundant, but if you need something likevar a float64 = 100When you use it that way, it’s useful.

Pointer to 2.

There’s nothing to say about Pointers, there’s secondary Pointers that need to be said, but for some reason I wrote it in another article: my other article.

3. The scope

As with JS, you can even use curly braces without keywords. Even the scope chain is used. But not completely, because the for, if, etc in go have an implicit scope:

for i := 0; i < 10; i++ {
    fmt.Println(i)
    i := 0
    fmt.Println(i)
}
// Do you think it will go on forever? In fact, not
// The loop will loop 10 times
Print 0,1,2... 9
// The second print will print 10 zeros
Copy the code

The for initializer is in the same scope as the for initializer, so it can be accessed. But no, that’s the magic of Go. The entire code actually looks something like this:

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

That is, the block in braces and the block that initializes I are not in the same scope, but are nested, so you can use I, but you can’t change the outside I. So this cycle must be going around 10 times.

That doesn’t mean you can’t change the I on the inside and the I on the outside. As long as you don’t declare the new I inside. I can change the external I to skip multiple loops. Especially when reading bytes.

for i := 0; i < 10; i++ {
    i += 1
    fmt.Println(i)
}
/ / output 1,3,5,7,9
Copy the code