create Golang project with basic concepts

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值