学习Golang的过程中,练习必不可少,俗话说的好 Talk is cheap,show me the code,学完Golang基本语法,是需要适当做一些练习加深理解的,虽然很很很简单!但是本人Java转go,语法还是要多熟悉,秉承多写一遍就多一次理解的原则,开始吧~
- 练习1- 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23- //练习1 
 //编写代码分别定义一个整型、浮点型、布尔型、字符串型变量,使
 //用fmt.Printf()搭配%T分别打印出上述变量的值和类型。
 package main
 
 import (
 "fmt"
 )
 
 func test1() {
 a := 10
 b := 1.0
 c := false
 d := "哈哈哈"
 fmt.Printf("a的类型为%T\n", a)
 fmt.Printf("b的类型为%T\n", b)
 fmt.Printf("c的类型为%T\n", c)
 fmt.Printf("d的类型为%T\n", d)
 }
 
 func main() {
 test1()
 }
- 练习2- 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23- //练习2 
 //编写代码统计出字符串"hello沙河小王子"中汉字的数量
 package main
 
 import (
 "fmt"
 "unicode"
 )
 
 func test2() {
 s := "hello沙河小王子"
 count := 0
 for _, c := range s {
 if unicode.Is(unicode.Han, c) {
 count = count + 1
 }
 }
 fmt.Printf("字符串包含%v个中文", count)
 }
 
 func main() {
 test2()
 }
- 练习3- 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21- //练习3 
 //求数组[1, 3, 5, 7, 8]所有元素的和
 package main
 
 import (
 "fmt"
 "unicode"
 )
 
 func test3() {
 arr := [...]int{1, 3, 5, 7, 9}
 count := 0
 for _, v := range arr {
 count = count + v
 }
 fmt.Printf("result:%v", count)
 }
 
 func main() {
 test3()
 }
- 练习4- 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27- //练习4 
 //找出数组中和为指定值的两个元素的下标,
 //比如从数组[1, 3, 5, 7, 8]中找出和为8的两个元素的下标分别为(0,3)和(1,2)。
 package main
 
 import "fmt"
 
 func test4() (int, int) {
 result := 8
 resultmap := make(map[int]int)
 arr := [...]int{1, 3, 5, 7, 9}
 for index, v := range arr {
 gapv := result - v
 va, ok := resultmap[gapv]
 if ok {
 return index, va
 }
 resultmap[v] = index
 }
 fmt.Println(resultmap)
 return 0, 0
 }
 
 func main() {
 res1, res2 := test4()
 fmt.Printf("%v,%v", res1, res2)
 }
Talk is cheap,show me the code~
  