说明
下面是我在学习Go期间,整理的一部分数据(只记录了部分对我而言有用的),可以用作参考.不定期更新.
第一个Go程序
在Windows上安装Go,必须在系统环境变量中配置变量:GOPATH(值为Windows路径),Go只会编译执行GOPATH目录中的.go文件.
package main import "fmt" /* 1.文件名:main.go 2.编译:go build main.go 3.执行:go run main 第一个go程序. 2017.3.3 prd. */ func main() { fmt.Println("Hello World!") }
变量声明及类型
变量声明
在Go中变量声明,有如下方式:
1.
// 声明不赋值,使用默认值
var age int
2.
// 根据值判断类型
var vname = value
3.
// 省略var,左侧的变量不能已经被声明过.
vname:=value
多个变量
var age,info,name type
var age,info,name = a1,a2,a3
age,info,name := a1,a2,a3
var (
age type
name type
)
在同一个代码块中,age:=10只能存在一次(也就是不能在写一个age:=10);另外,在同一个代码块中如果定义了变量没有使用,编译会报错,给变量赋值也不行,变量必须要使用.
如果要交换两个变量的值,则可以直接:
a,b = b,a
常量
定义之后不会被修改的变量,定义方式:
const name = “job”
或者
const name string = “job”
类型
Go中有以下类型:
类型 | 描述 |
布尔 | 只有两个值,true或者false |
数字 | 整型int和浮点型float. |
字符串 | 一串字符表示,Go的字节使用UTF-8编码标识Unicode文本 |
派生 | 1.指针;2.数组;3.结构化类型(struct);4.联合体类;5.函数类型;6.切片类型 ;7.接口;8.Map类型;9.Channel类型 |
整数类型最大值与最小值(获取方式下面有调用示例)
类型 | 描述 |
uint8 | 最小值:0,最大值:调用math.MaxUint8 |
uint16 | 最小值:0,最大值:调用math.MaxUint16 |
uint32 | 最小值:0,最大值:调用math.MaxUint32 |
uint64 | 最小值:0,最大值:调用math.MaxUint64 |
int8 | 最小值:MinInt8,最大值:调用math.MaxInt8 |
int16 | 最小值:MinInt16,最大值:调用math.MaxInt16 |
int32 | 最小值:MinInt32,最大值:调用math.MaxInt32 |
int64 | 最小值:MinInt64,最大值:调用math.MaxInt64 |
调用示例 package main import ( "fmt" "math" ) /* Go数字类型最大值与最小值 2017.4.7 prd. */ func main() { fmt.Println("Hello World!") fmt.Println(math.MinInt32) // int32 最小值 fmt.Println(math.MaxInt32) // int32 最大值 fmt.Println(math.MaxUint32) // uint32 最大值,最小值:0 } |
浮点类型:
类型 | 描述 |
float32 | 调用:math.MaxFloat32 |
float64 | 调用:math.MaxFloat32 |
complex64 | 调用:math.SmallestNonzeroFloat32 |
complex128 | 调用:math.SmallestNonzeroFloat64 |
Go时间格式化
Go是个奇葩!!!
我们一般的格式化是:yyyy-MM-dd HH:mm:ss,在Go中必须是这样:”2006-01-02 15:04:05″,嗯,你没看错,据说这个时间是Go诞生的时间.
那么使用格式化,例子来了:
package main import ( "fmt" "time" ) /* Go时间格式化 2017.4.7 prd. */ func main() { fmt.Println("Hello World!") fmt.Println(time.Now().Format("2006-01-02 15:04:05")) fmt.Println(time.Now().Format("2006-01-02 15:04")) fmt.Println(time.Now().Format("200601021504")) fmt.Println(time.Now().Format("2006/01/02 15/04")) fmt.Println(time.Now().Format("2006-01-02")) /* 官方常量定义(更多请参考官方文档的time包): const ( ANSIC = "Mon Jan _2 15:04:05 2006" UnixDate = "Mon Jan _2 15:04:05 MST 2006" RubyDate = "Mon Jan 02 15:04:05 -0700 2006" RFC822 = "02 Jan 06 15:04 MST" RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone RFC850 = "Monday, 02-Jan-06 15:04:05 MST" RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone RFC3339 = "2006-01-02T15:04:05Z07:00" RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" Kitchen = "3:04PM" // Handy time stamps. Stamp = "Jan _2 15:04:05" StampMilli = "Jan _2 15:04:05.000" StampMicro = "Jan _2 15:04:05.000000" StampNano = "Jan _2 15:04:05.000000000" ) */ fmt.Println(time.Now().Format(time.RFC3339)) }