go语言入门
下载编译器安装包,解压并设置环境变量
path=D:\Go\bin
package main import "fmt" func main() { fmt.Println("Hello, World!") }
D:\study\go>go run test.go
Hello, World!
package main import "fmt" import "unsafe" // 为fmt起别名为fmt2 //import fmt2 "fmt" //省略调用(不建议使用): // 调用的时候只需要Println(),而不需要fmt.Println() //import . "fmt" //也可以同时导入多个: /* import { "fmt", "io" } */ //全局变量可以声明后不使用,局部变量声明后必须使用,否则会报编译错误 var temp_var int = 3 // 常量定义 const PI = 3.14 func main() { testBase() testData() testConst() testIota() testSymbol() testJudge() testData1() testArrayAndPointer() testStruct() testSlice() testRange() testMap() testFactorial() testSwapType() testInterface() } func testBase() { // 单行注释 //如果你打算将多个语句写在同一行,它们则必须使用 ; 人为区分,但在实际开发中我们并不鼓励这种做法。 fmt.Println("Hello, World!");fmt.Println("mutian!") /* 多行注释 */ //变量声明 var a int = 1 var b int b = 2 var c = 3 d := 4 fmt.Println(a, b, c, d) } func testData() { //go 1.9版本对于数字类型,无需定义int及float32、float64,系统会自动识别 //float64 a = 1.5 var a = 1.5 fmt.Println(a) var value1 bool //一般声明 默认值为false fmt.Println(value1) value1 = true //赋值操作 fmt.Println(value1) value2 := false //简短声明 fmt.Println(value2) var enabled, disabled = true, false // 忽略类型的声明 fmt.Println(enabled, disabled) var ( m bool n bool ) fmt.Println(m, n) // 一般类型声明 type newType int var x newType = 3 fmt.Println(x); var q, p int = 2, 3 fmt.Println(q, p) q, p = p, q //交换q和p fmt.Println(q, p) } func testConst() { //常量中的数据类型只可以是布尔型、数字型(整数型、浮点型和复数)和字符串型。 //可以省略类型说明符 [type],因为编译器可以根据变量的值来推断其类型。 //常量的定义格式:const identifier [type] = value //显式类型定义 const a string = "abc" // 隐式类型定义 const b = "abc" const c, d, e = 1, false, "str" //多重赋值 //常量还可以用作枚举: const ( Unknown = 0 Female = 1 Male = 2 ) const ( f = "abc" g = len(a) // 字符串类型在 go 里是个结构, 包含指向底层数组的指针和长度,这两部分每部分都是 8 个字节 //所以字符串类型大小为 16 个字节。 h = unsafe.Sizeof(f) ) fmt.Println(f, g, h) } func testIota() { //1. iota,特殊常量,可以认为是一个可以被编译器修改的常量。 //2. 在每一个const关键字出现时,被重置为0,然后再下一个const出现之前, //每出现一次iota,其所代表的数字会自动增加1。 //3. const枚举时,每个表达式没有显示表达式时,隐式为上一个表达式,而且iota+ = 1 const ( a = iota //0 b //1 c //2 d = "ha" //独立值,iota += 1 e //"ha" iota += 1 f = 100 //iota +=1 g //100 iota +=1 h = iota //7,恢复计数 i //8 ) fmt.Println(a,b,c,d,e,f,g,h,i) // 0 1 2 ha ha 100 100 7 8 const ( j=1<<iota k=3<<iota l m ) fmt.Println(j, k, l, m) //1 6 12 24 } func testSymbol() { var a int = 4 var b int32 var c float32 var ptr *int /* 运算符实例 */ fmt.Printf("第 1 行 - a 变量类型为 = %T\n", a ); // int fmt.Printf("第 2 行 - b 变量类型为 = %T\n", b ); // int32 fmt.Printf("第 3 行 - c 变量类型为 = %T\n", c ); // float32 /* & 和 * 运算符实例 */ ptr = &a // 'ptr' 包含了 'a' 变量的地址 fmt.Printf("a 的值为 %d\n", a); fmt.Printf("*ptr 为 %d\n", *ptr); } func testJudge() { //while(count<100) { //go没有while var sum int = 0 for temp := 1; temp <= 100; temp++ { sum += temp } fmt.Println("sum:", sum); } func testData1() { // for 循环的 range 格式可以对 slice、map、数组、字符串等进行迭代循环。格式如下: //for key, value := range oldMap { // newMap[key] = value //} numbers := [6]int{1, 2, 3, 5} for i,x:= range numbers { fmt.Printf("第 %d 位 x 的值 = %d\n", i,x) } x, y := "abc", "def" x, y = swap(x, y) fmt.Println(x, y) } func swap(x, y string) (string, string) { return y, x } //pointer默认值是nil func testArrayAndPointer() { //var balance1 [10] float32 //var balance2 = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0} var a int = 10 fmt.Printf("变量的地址: %x\n", &a) // 当一个指针被定义后没有分配到任何变量时,它的值为 nil。 // nil 指针也称为空指针。 // nil在概念上和其它语言的null、None、nil、NULL一样,都指代零值或空值。 // 一个指针变量通常缩写为 ptr。 var ptr *int = &a if (ptr != nil) { fmt.Printf("ip: %x\n", ptr) } } func testStruct() { type Books struct { title string book_id int } var book1 Books book1.title = "best" book1.book_id = 123 fmt.Printf( "Book1 title : %s\n", book1.title) fmt.Printf( "Book1 title : %d\n", book1.book_id) book2 := Books {"xiaoming", 321} fmt.Printf( "Book2 title : %s\n", book2.title) fmt.Printf( "Book2 title : %d\n", book2.book_id) } func testSlice() { //Go 语言切片(Slice): 未指定大小的数组来定义切片 //如果指定大小那就是数组,这里不指定大小就是切片 var s1 = [] int {1, 2, 3, 4} fmt.Println(s1) printSlice(s1) var sNil []int //不赋值则为nil fmt.Println("sNil is nil:", sNil == nil); printSlice(sNil) var s2 [] int = s1[:] printSlice(s2) var s3 [] int = s1[:2] printSlice(s3) var s4 [] int = s1[2:] printSlice(s4) var s5 [] int = s1[1:2] printSlice(s5) var s6 [] int = append(s1, 5, 6) printSlice(s6) // [1 2 3 4 5 6] var s7 [] int = make([]int, 8, 10) copy(s7, s6) //copy的第一个参数必须是已经赋值了的切片,否则拷贝结果为空 printSlice(s7) //[1 2 3 4 5 6 0] var s8 [] int = make([]int, 3, 10) copy(s8, s6) printSlice(s8) //[1 2 3] fmt.Println("---------") //使用make([]T, length, capacity)声明切片,其中capacity是可选参数 var s100 [] int = make([]int, 3, 5) //var s100 = make([]int, 3, 5) //这种写法貌似也可以啊 printSlice(s100) } func printSlice(x [] int) { fmt.Printf("len:%d, cap:%d, slice:%v\n", len(x), cap(x), x) } func testRange() { // Go 语言中 range 关键字用于 for 循环中迭代数组(array)、切片(slice)、通道(channel)或集合(map)的元素。 //在数组和切片中它返回元素的索引和索引对应的值,在集合中返回 key-value 对的 key 值。 //这是我们使用range去求一个slice的和。使用数组跟这个很类似 nums := []int{2, 3, 4} sum := 0 for _, num := range nums { sum += num } fmt.Println("sum:", sum) //在数组上使用range将传入index和值两个变量。上面那个例子我们不需要使用该元素的序号, //所以我们使用空白符"_"省略了。有时侯我们确实需要知道它的索引。 for i, num := range nums { if num == 3 { fmt.Println("index:", i) } } //range也可以用在map的键值对上。 kvs := map[string]string{"a": "apple", "b": "banana"} for k, v := range kvs { fmt.Printf("%s -> %s\n", k, v) } } func testMap() { var countryMap map[string] string //countryMap = make(map[string]string) countryMap = map[string]string{"France":"Paris", "Italy": "Rome", } //插入元素 countryMap["China"] = "BeiJing" countryMap[ "Japan" ] = "东京" delete(countryMap, "Japan") for key, value := range countryMap { fmt.Println(key, value) } /*查看元素在集合中是否存在 */ captial, ok := countryMap [ "America" ] /*如果确定是真实的,则存在,否则不存在 */ if (ok) { fmt.Println("美国的首都是", captial) } else { fmt.Println("没找到") } } func testFactorial() { var i int = 15 fmt.Printf("%d 的阶乘是 %d\n", i, Factorial(uint64(i))) } //注意返回参数 竟然带参数名 func Factorial(n uint64)(result uint64) { if (n > 0) { result = n * Factorial(n-1) return result } return 1 } func testSwapType() { var sum int = 17 var count int = 5 var meat float32 meat = float32(sum) / float32(count) fmt.Println(meat) } //Go 语言接口 type Phone interface { call() price() int } type NokiaPhone struct { } func (nokiaPhone NokiaPhone) call() { fmt.Println("I am Nokia, I can call you!") } func (nokiaPhone NokiaPhone) price() int { return 100 } type IPhone struct { } func (iPhone IPhone) call() { fmt.Println("I am iPhone, I can call you!") } func (iPhone IPhone) price() int { return 200 } func testInterface() { var phone Phone phone = new(NokiaPhone) phone.call() fmt.Println(phone.price()) phone = new(IPhone) phone.call() fmt.Println(phone.price()) }
D:\study\go>go run test.go
Hello, World!
mutian!
1 2 3 4
1.5
false
true
false
true false
false false
3
2 3
3 2
abc 3 16
0 1 2 ha ha 100 100 7 8
1 6 12 24
第 1 行 - a 变量类型为 = int
第 2 行 - b 变量类型为 = int32
第 3 行 - c 变量类型为 = float32
a 的值为 4
*ptr 为 4
sum: 5050
第 0 位 x 的值 = 1
第 1 位 x 的值 = 2
第 2 位 x 的值 = 3
第 3 位 x 的值 = 5
第 4 位 x 的值 = 0
第 5 位 x 的值 = 0
def abc
变量的地址: c0420521c8
ip: c0420521c8
Book1 title : best
Book1 title : 123
Book2 title : xiaoming
Book2 title : 321
[1 2 3 4]
len:4, cap:4, slice:[1 2 3 4]
sNil is nil: true
len:0, cap:0, slice:[]
len:4, cap:4, slice:[1 2 3 4]
len:2, cap:4, slice:[1 2]
len:2, cap:2, slice:[3 4]
len:1, cap:3, slice:[2]
len:6, cap:8, slice:[1 2 3 4 5 6]
len:8, cap:10, slice:[1 2 3 4 5 6 0 0]
len:3, cap:10, slice:[1 2 3]
---------
len:3, cap:5, slice:[0 0 0]
sum: 9
index: 1
a -> apple
b -> banana
France Paris
Italy Rome
China BeiJing
没找到
15 的阶乘是 1307674368000
3.4
I am Nokia, I can call you!
100
I am iPhone, I can call you!
200