Перейти к содержимому
Обложка сообщества Разное

Go as a first language

In my previous post I described Go in a general view. In this post I am going to write, so far as possible in a practical view.

First of all, in my point of view, Go is a perfect language as a teaching language. If someone started to dive into programming world from a different background, it is very important their first impression about programming language they are going to learn.

Before knowing Go, I thought Python suits perfectly as a first learning language.
But now I am not sure, because spaces/tabs adding some meanings to the code may be very confusing.

1. A + B

package main

import "fmt"

func main() {
        var a, b int
        fmt.Scanf("%d%d", &a, &b)
        fmt.Print(a + b)
}

Isn't it looks like C/C++? By the way, in my opinion, C++ is not good as a first language, because C++ is difficult even for experienced C++ developers :).
I think, I know about %5 (if not less) from C++'s specifications. A lot of rules and old language, thus overcomplicated. If you try to search something simple in forums, you will find dozens of different answers. In a result, you won't feel learning progress.

2. If

package main

import "fmt"

func main() {
        var n int
        fmt.Scanf("%d", &n)
        if n%2 == 0 {
                fmt.Println("Number is even")
        } else {
                fmt.Println("Number is odd")
        }
}

Nothing special? Yes, but there are some parts I like here.

The "If" statement doesn't need to be surrounded by brackets "()". If you try to surround it, "Gofmt" tool will delete it for you on a save. Thanks to "Gofmt" tool, codes will look like the same, which is amazing for learners.

Unlike many other languages, you can't write a single statement without braces "{}", i.e the following code won't compile:

if n%2 == 0 
    fmt.Println("Number is even")
else 
    fmt.Println("Number is odd")

I like this strictness, because you don't have to learn about when to put braces and when not. In addition, in many language's style guides (e.g java style guide) recommend to put braces even when they are optional. Fortunately, "Go" has only one way :).

3. For and while

package main

import "fmt"

func main() {
        var n int
        sum := 0
        n = 10
        for i := 0; i < n; i++ {
                sum += i
        }
        fmt.Println(sum)
}

Try to guess, will this code compile?
If yes, what is the difference between ":=" and "=" ?

Go's syntax does not provide a while loop. Seriously, why we need while, when for can do the same?

for ;i < n; {
    sum += i
}

If you try to save, "Gofmt" transforms it to even simpler code:

for i < n {
    sum += i
}

while (true) looks like this:

for {
}

4. Function

package main

import "fmt"

func triple(x int, y int) (int, int, string) {
        return x * 2, y * 3, "third"
}
func main() {
        fmt.Println(triple(1, 2))
}

A Function can return any number of variables, which is awesome.

package main

import "fmt"

func triple(x, y int) (a int, b int, s string) {
        a = x * 2
        b = y * 3
        s = "third"
        return
}
func main() {
        fmt.Println(triple(1, 2))
}

The same code, but showing different features of a function. Concretely, variables in parameters can share a type, return values can be named.

5. Arrays and slices.
Nothing to say about arrays, it is similar to arrays in other languages, but slices are awesome. We can think "slice" as a dynamic array.

package main

import "fmt"

func main() {
        a := make([]int, 5)
        for i := 0; i < 5; i++ {
                a[i] = i * i
        }
        b := a[1:4]
        fmt.Println(b) // [1, 4, 9]

        a = append(a, 111)
        for i, v := range a {
                fmt.Println(i, v)
        }
}

Slice is kind of similar to Python's list but isn't flexible as Python's. "Range" iterates over a slice and returns index, value (one of them can be omitted as "_").

6. Defer

package main

import "fmt"

func main() {
        defer fmt.Print("world")
        fmt.Print("hello ")
}

The output is: "Hello world". Defer is used to call the function after performing the surrounding function. It is commonly used to perform cleanup, e.g:

package main

import (
        "fmt"
        "os"
)

func main() {
        f, err := os.Create("~/a.txt")
        defer f.Close()
        if err != nill {
            return
        }
        // Do some other stuff
}

Now you don't have to worry about closing file before every "return" operation, "defer" will take care about it for you.

To sum up, Go is very awesome language. I can come up with several areas where Golang can be used optimally. One of them is as a learning language for kids, students (Maybe still Python better?).

Which programming language do you like most?

4
0
440

Еще по теме

Go as a first language - Yvision.kz