Golang Quick Start
这两天在学习G语言, 在看了go指南和一份go crash course的视频之后, 写代码试了试
go程序从main包下面的main函数开始执行
package main
导入其他的包
import ( "fmt" "math" "strconv" )
定义一个结构体, go语法上没有复杂的对象继承关系
type Person struct {
name string
age int
}
类型别名
// use a alias name for person type Teacher Person
使用变量, 可以用:= 初始化并且声明一个变量, 但是不能在函数外面使用这个技巧
func variable_01() {
age := 20
msg := "this is a message from jack whose age is " + strconv.Itoa(age)
fmt.Println(msg)
}
由于go是由包构成的程序, 区分包内对外开放的成员的方法是, 以大写字母开头的成员是对外开放的
// in go language, only Capitalized member will be exported to other package
func exportName_03() {
fmt.Println("this is PI :", math.Pi)
}
函数的返回值可以是多个
// function can return more than one return value
func greaterThanYourNumber_04(yournumber int) (number int, err error) {
return yournumber+1, nil;
}
函数参数类型的省略规则
// this function could use to swap two int number
func functionOmitType_05(a, b int) (c, d int) {
c, d = b, a
return
}
未初始化的变量会自动给默认值
// use some variables that is not initialized
func useUnInitializedNumber_06() {
var aint int
var afloat float64
var abool bool
var astring string
fmt.Println(aint, afloat, abool, astring)
}
类型转换. go在赋值的过程中不会进行隐形的类型转换, 除了`:=`这样的短声明
// type cast
func typeCast_07() {
// we have a float32 number, by default a decimal literal should be float64
decimal := 300.0
fmt.Printf("%T\n", decimal)
var afloat32 float32
afloat32 = 200.0 // it works
fmt.Println(afloat32)
aint := 200
afloat32 = float32(aint)
}
使用常量
// const
// go use capitalized word to indicate a const instead of all upper case
func constValues_08() {
const BigNumber = 1 << 200
//fmt.Println("big number:", BigNumber)
//# command-line-arguments
//.\main.go:74:14: constant 1606938044258990275541962092341162602522202993782792835301376 overflows int
}
只有一种for循环
// there is only one kind of loop in go
func forLoop_09() {
// like normal for loop in other language
// but we can't add a () pair on the condition expression
fmt.Println("--- normal for loop")
for i := 0; i < 10; i++ {
fmt.Println(i)
}
fmt.Println("--- like a while loop")
sum := 0
i := 0
for sum != 55 {
i += 1
sum += i
}
fmt.Println("from 1 adds to", i, "the sum will equals 55")
// infinite loop
//for {
// // do nothing
//}
}
if语句也有初始化部分
// if statement could have a initalize expression, and this variable could be used in else statement
func ifStatement_10() {
// we could not use a `,` to separate several variable short declaration
if i := 100; i < 10 {
fmt.Println("100 < 10")
} else {
// we can access the variable i in this position
fmt.Println(i, "<", 10)
}
// but we could do this
var a, b int
if a, b = 100, 10; a < b {
}
// may we can do this
if a, b := 100, 10; a > b {
}
}
switch的默认值
// use switch statement
func useSwitch_11() {
fmt.Println("--- use switch statement")
expr := 100
switch expr {
case 100:
fmt.Println(100)
fmt.Println("case will not go down even there is no break statement")
case 200:
fmt.Println(200)
default:
fmt.Println("nothing")
}
fmt.Println("--- use switch's default value true")
switch {
case true:
fmt.Println("swith's default value is true, if there is no expression")
case false:
fmt.Println("this shouldn't appear on the screen")
default:
fmt.Println("default shouldn't appear on the screen")
}
fmt.Println("--- switch's flow")
switch 1 {
default:
fmt.Println("default 3 2 1")
case 3:
fmt.Println(3)
case getTwo():
fmt.Println(2)
case 1:
fmt.Println(1)
}
}
defer可以推迟在函数块退出之后执行, 而defer的对象必须是函数调用, 函数参数的值立即计算
// use defer
func useDefer_12() {
num := 100
defer fmt.Println("1. defer num:", num)
defer fmt.Println("2. defer num:", num)
defer fmt.Println("3. defer num:", num)
// expression in defer must be function call
//defer two:= getTwo()
num = 200
fmt.Println("num is", num)
}
使用指针, 指针只有解引用运算, 没有+法运算
func usePointer_13() {
num := 200
p := &num
fmt.Println("p's value is", *p, "p's address is", p)
type Person struct {
name string
age int
}
// operate + not defined on *int, or something else
//p = p + p
//p += 1
//p++
//++p
pointerToPerson := &Person{"jack", 18}
fmt.Println("without explicit dereference", pointerToPerson)
fmt.Println("[explicit dereference] *pointerToPerson:", *pointerToPerson)
fmt.Println("[implicit dereference] pointerToPerson.name:", pointerToPerson.name)
}
函数块内也可以定义结构体
func useStruct_14() {
type Vertex struct {
x, y int
}
fmt.Println(Vertex{x:100})
}
数组的使用, 数组语法上无法改变大小,但是可以绕过
// array's declaration and initialization
func useArray_15() {
{
var array [3] string;
array[0] = "jack";
array[1] = "unname";
array[2] = "go"
fmt.Println(array)
}
{
array := [3]int{1, 2, 3}
fmt.Println(array)
}
}
切片的使用
// slice and slice on slice
func useSlice_16() {
fmt.Println("--- Make slice")
// make slice
{
var emptySlice []int
fmt.Println("emptySlice should be nil", emptySlice == nil, "capacity and lenth are 0")
//fmt.Println("try to access a invalid index will cause panic", emptySlice[1])
ints := make([]int, 10)
fmt.Println("ints's capacity is", cap(ints), "lenght is", len(ints))
for i := range ints {
fmt.Printf("%d\t" , i)
}
// it's capacity will increase as the append function be called
fmt.Println()
}
fmt.Println("--- Use slice")
// use slice
{
ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
// array's slice
slice01 := ints[1: 5]// 2, 3, 4, 5
fmt.Println(slice01)
// slice on slice
slice02 := slice01[1:3] // 3, 4
fmt.Println(slice02)
// change element
slice02[0] = 100 // 3 should be place with 100
fmt.Println(ints)
slice02 = append(slice02, 200)
fmt.Println(ints) // [1 2 100 4 200 6 7 8 9]
}
}
全部代码:
package main
// import strconv for integer to string
// go language does not support the + operator for two diffrent type
import (
"fmt"
"math"
"strconv"
)
type Person struct {
name string
age int
}
// use a alias name for person
type Teacher Person
func variable_01() {
age := 20
msg := "this is a message from jack whose age is " + strconv.Itoa(age)
fmt.Println(msg)
}
// we usually can use type to give a alias name to a type
func alias_02() {
jack := Teacher{name:"jack", age:22}
fmt.Println(jack)
}
// in go language, only Capitalized member will be exported to other package
func exportName_03() {
fmt.Println("this is PI :", math.Pi)
}
// function can return more than one return value
func greaterThanYourNumber_04(yournumber int) (number int, err error) {
return yournumber+1, nil;
}
// this function could use to swap two int number
func functionOmitType_05(a, b int) (c, d int) {
c, d = b, a
return
}
// use some variables that is not initialized
func useUnInitializedNumber_06() {
var aint int
var afloat float64
var abool bool
var astring string
fmt.Println(aint, afloat, abool, astring)
}
// type cast
func typeCast_07() {
// we have a float32 number, by default a decimal literal should be float64
decimal := 300.0
fmt.Printf("%T\n", decimal)
var afloat32 float32
afloat32 = 200.0 // it works
fmt.Println(afloat32)
aint := 200
afloat32 = float32(aint)
}
// const
// go use capitalized word to indicate a const instead of all upper case
func constValues_08() {
const BigNumber = 1 << 200
//fmt.Println("big number:", BigNumber)
//# command-line-arguments
//.\main.go:74:14: constant 1606938044258990275541962092341162602522202993782792835301376 overflows int
}
// there is only one kind of loop in go
func forLoop_09() {
// like normal for loop in other language
// but we can't add a () pair on the condition expression
fmt.Println("--- normal for loop")
for i := 0; i < 10; i++ {
fmt.Println(i)
}
fmt.Println("--- like a while loop")
sum := 0
i := 0
for sum != 55 {
i += 1
sum += i
}
fmt.Println("from 1 adds to", i, "the sum will equals 55")
// infinite loop
//for {
// // do nothing
//}
}
// if statement could have a initalize expression, and this variable could be used in else statement
func ifStatement_10() {
// we could not use a `,` to separate several variable short declaration
if i := 100; i < 10 {
fmt.Println("100 < 10")
} else {
// we can access the variable i in this position
fmt.Println(i, "<", 10)
}
// but we could do this
var a, b int
if a, b = 100, 10; a < b {
}
// may we can do this
if a, b := 100, 10; a > b {
}
}
// use switch statement
func useSwitch_11() {
fmt.Println("--- use switch statement")
expr := 100
switch expr {
case 100:
fmt.Println(100)
fmt.Println("case will not go down even there is no break statement")
case 200:
fmt.Println(200)
default:
fmt.Println("nothing")
}
fmt.Println("--- use switch's default value true")
switch {
case true:
fmt.Println("swith's default value is true, if there is no expression")
case false:
fmt.Println("this shouldn't appear on the screen")
default:
fmt.Println("default shouldn't appear on the screen")
}
fmt.Println("--- switch's flow")
switch 1 {
default:
fmt.Println("default 3 2 1")
case 3:
fmt.Println(3)
case getTwo():
fmt.Println(2)
case 1:
fmt.Println(1)
}
}
func getTwo() int {
return 2;
}
// use defer
func useDefer_12() {
num := 100
defer fmt.Println("1. defer num:", num)
defer fmt.Println("2. defer num:", num)
defer fmt.Println("3. defer num:", num)
// expression in defer must be function call
//defer two:= getTwo()
num = 200
fmt.Println("num is", num)
}
func main() {
// 01, variable
//variable_01()
// 02.struct alias name
//alias_02()
// 03.export name
//exportName_03()
// 04. use function
//number := 200
//fmt.Println("your number is set to", number)
//newNumber, _ := greaterThanYourNumber(number)
//fmt.Println("But, my number would be ", newNumber)
// 05. omit parameter type or return type
//a, b := 0, 1
//a, b = functionOmitType_05(a, b)
//fmt.Println(a, b)
// 06. use values without initialize
//useUnInitializedNumber_06()
// 07. type cast,sometimes go language won't do implicit type cast sometimes
//typeCast_07()
// 08. use const values
//constValues_08()
// 09. for loop
//forLoop_09()
// 10. if statement
//ifStatement_10()
// 11. use switch
//useSwitch_11()
// 12. defer
//useDefer_12()
// 13. pointer
//usePointer_13()
// 14. use struct, we can define a struct in method, but we can not define the corresponded method receiver
//useStruct_14()
// 15. use array, example: array := [3]int{1, 2, 3}
//useArray_15()
// 16. use slice
useSlice_16()
// 17.
}
// slice and slice on slice
func useSlice_16() {
fmt.Println("--- Make slice")
// make slice
{
var emptySlice []int
fmt.Println("emptySlice should be nil", emptySlice == nil, "capacity and lenth are 0")
//fmt.Println("try to access a invalid index will cause panic", emptySlice[1])
ints := make([]int, 10)
fmt.Println("ints's capacity is", cap(ints), "lenght is", len(ints))
for i := range ints {
fmt.Printf("%d\t" , i)
}
// it's capacity will increase as the append function be called
fmt.Println()
}
fmt.Println("--- Use slice")
// use slice
{
ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
// array's slice
slice01 := ints[1: 5]// 2, 3, 4, 5
fmt.Println(slice01)
// slice on slice
slice02 := slice01[1:3] // 3, 4
fmt.Println(slice02)
// change element
slice02[0] = 100 // 3 should be place with 100
fmt.Println(ints)
slice02 = append(slice02, 200)
fmt.Println(ints) // [1 2 100 4 200 6 7 8 9]
}
}
// array's declaration and initialization
func useArray_15() {
{
var array [3] string;
array[0] = "jack";
array[1] = "unname";
array[2] = "go"
fmt.Println(array)
}
{
array := [3]int{1, 2, 3}
fmt.Println(array)
}
}
func useStruct_14() {
type Vertex struct {
x, y int
}
fmt.Println(Vertex{x:100})
}
func usePointer_13() {
num := 200
p := &num
fmt.Println("p's value is", *p, "p's address is", p)
type Person struct {
name string
age int
}
// operate + not defined on *int, or something else
//p = p + p
//p += 1
//p++
//++p
pointerToPerson := &Person{"jack", 18}
fmt.Println("without explicit dereference", pointerToPerson)
fmt.Println("[explicit dereference] *pointerToPerson:", *pointerToPerson)
fmt.Println("[implicit dereference] pointerToPerson.name:", pointerToPerson.name)
}
// we can not use short declaration variable in this place
//aNumber := 100
// data types
/*
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // uint8's alias
rune // int32's alias unicode
float32 float64
complex64 complex128
*/

浙公网安备 33010602011771号