Golang基础语法(一)

 学习一门新的语言无非就是从基本的语法开始的。通过语法书来学习语言毕竟是非常枯燥的,所以我们不妨从最简单的例子开始学习一门新的语言。例子不多,但是有代表性。


    (a)最简单的代码

[cpp]  view plain  copy
  1. package main  
  2.   
  3. import "fmt"  
  4.   
  5.   
  6. func main() {  
  7.   
  8.         fmt.Println("hello, world")  
  9. }  

     (b)基本的函数

[cpp]  view plain  copy
  1. package main  
  2.   
  3. import "fmt"  
  4.   
  5. func sub(a int, b intint {  
  6.   
  7.         return a - b;  
  8. }  
  9.   
  10. func main() {  
  11.   
  12.         fmt.Println(sub(2, 3))  
  13. }  

     (c)if语句学习

[cpp]  view plain  copy
  1. package main  
  2.   
  3. import "fmt"  
  4.   
  5. func compare(a int, b int) {  
  6.   
  7.         if(a > b) {  
  8.                 fmt.Println("greater")  
  9.         }else{  
  10.                 fmt.Println("smaller")  
  11.         }  
  12. }  
  13.   
  14. func main() {  
  15.   
  16.         compare(3, 2)  
  17. }  

    (d)switch语句学习

[cpp]  view plain  copy
  1. package main  
  2.   
  3. import "fmt"  
  4.   
  5. func test(a int) {  
  6.   
  7.         switch (a) {  
  8.   
  9.                 case 1:  
  10.                         fmt.Println("1")  
  11.   
  12.                 case 2:  
  13.                         fmt.Println("2")  
  14.   
  15.                 default:  
  16.                         fmt.Println("error")  
  17.   
  18.         }  
  19.   
  20. }  
  21.   
  22. func main() {  
  23.   
  24.         test(1)  
  25.         test(2)  
  26.         test(3)  
  27. }  

     (e)循环语句学习

[cpp]  view plain  copy
  1. package main  
  2.   
  3. import "fmt"  
  4.   
  5. func show(data int) {  
  6.   
  7.         var index int  
  8.         index = 0  
  9.   
  10.         for {  
  11.   
  12.                 if(index >= data) {  
  13.   
  14.                         break  
  15.                 }  
  16.   
  17.                 fmt.Println(index)  
  18.                 index ++  
  19.                 continue  
  20.   
  21.         }  
  22. }  
  23.   
  24. func main() {  
  25.   
  26.         show(10)  
  27. }  

    (f)结构体学习

[cpp]  view plain  copy
  1. package main  
  2.   
  3. import "fmt"  
  4.   
  5. type node struct {  
  6.   
  7.         data int  
  8.   
  9. }  
  10.   
  11. func(p* node)set(val int)() {  
  12.   
  13.         p.data = val  
  14. }  
  15.   
  16. func(p* node)get() int {  
  17.   
  18.         return p.data;  
  19. }  
  20.   
  21.   
  22. func main() {  
  23.   
  24.         n := node{data: 10}  
  25.   
  26.         m := &n  
  27.         m.set(12)  
  28.         fmt.Println(m.get())  
  29. }  

猜你喜欢

转载自blog.csdn.net/littesss/article/details/78390466