Try Golang for the first time

Before everything stars, I need to download go from its website.
When I finish the installing, I can check where is my work directory by typing:

go env GOPATH

eg.

Hello World

Programs start running in package main. This program is using the packages with import paths "fmt" and "math/rand".

package main

import (
    "fmt"
    "math/rand"
)

And add one function in our file:

func main() {
    fmt.Printf("Hello World!")
}

Then save and file and type

go run main.go

And get the output:

We re done! This is my first hello world from Go!

Function

A function can take zero or more arguments.
Notice that the type comes after the variable name.

package main

import "fmt"

func add(x int, y int) int {
    return x + y
}

func main() {
    fmt.Println(add(42, 13))
}

A function can return any number of results.
The swap function returns two strings.

package main

import "fmt"

func swap(x, y string) (string, string) {
    return y, x
}

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

Go's return values may be named. If so, they are treated as variables defined at the top of the function.

package main

import "fmt"

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}

func main() {
    fmt.Println(split(17))
}

Variables

The var statement declares a list of variables; as in function argument lists, the type is last.
A var statement can be at package or function level. We see both in this example.

package main

import "fmt"

var c, python, java bool

func main() {
    var i int
    fmt.Println(i, c, python, java)
}

The output should be

0 false false false

A var declaration can include initializers, one per variable.
If an initializer is present, the type can be omitted; the variable will take the type of the initializer.

package main

import "fmt"

var i, j int = 1, 2

func main() {
    var c, python, java = true, false, "no!"
    fmt.Println(i, j, c, python, java)
}

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.

package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    c, python, java := true, false, "no!"

    fmt.Println(i, j, k, c, python, java)
}
CategoriesGoTags

Leave a Reply