1, create new project “test5_concept”
$ cd ~/project
$ mkdir test5_concept
$ cd test5_concept
$ touch concept.go
2,add following lines in “concept.go”
package main
import (
"fmt"
"time"
"math/rand"
)
const (
year int = 365
month int = 12
day int = 30
)
func init() {
// TEST 1, init() works in the first step by default
fmt.Println("This is init() of test5_concept/concept.go")
rand.Seed(time.Now().UnixNano())
}
func main() {
// TEST 2, generate ranndom value
fmt.Println("Generate a random number:", rand.Intn(7))
// TEST 3, function with multiple inputs
fmt.Println("Try add(3, 4) =", add(3, 4))
// TEST 4, function with multiple outputs
var _a, _b, _c int = 0, 0, 0
_a, _b, _c = swap(3, 4, 5)
fmt.Println("Try swap(3, 4, 5) =", _a, _b, _c)
// TEST 5, function with default output
fmt.Println("Try greet('little dog') =", greet("little dog"))
// TEST 6, print default initialized value
var default_n int
var default_b bool
var default_s string
defaultV(default_n, default_b, default_s)
// TEST 7, convert between int & float32
convertV(11, 2.2)
// TEST 8, const definition
display()
}
func add(a, b int) int {
return (a + b)
}
func swap(a, b, c int) (int, int, int) {
return c, b, a
}
func greet(name string) (greeting string) {
greeting = "Hello ! " + name
return
}
func defaultV(a int, b bool, c string) {
fmt.Println("default int =", a)
fmt.Println("default bool =", b)
fmt.Println("default string =", c)
}
func convertV(a int, b float32) {
fmt.Printf("raw: %T, %T\n", a, b)
fmt.Printf("raw: %T, %T\n", float32(a), int(b))
}
func display() {
fmt.Printf("year = %d, month = %d, day = %d\n", year, month, day)
}
6, run “concept.go”
go run concept.go
you should get result like this:
This is init() of test5_concept/concept.go
Generate a random number: 2
Try add(3, 4) = 7
Try swap(3, 4, 5) = 5 4 3
Try greet('little dog') = Hello ! little dog
default int = 0
default bool = false
default string =
raw: int, float32
raw: float32, int
year = 365, month = 12, day = 30