Golang基礎語法(一)
阿新 • • 發佈:2018-12-23
學習一門新的語言無非就是從基本的語法開始的。通過語法書來學習語言畢竟是非常枯燥的,所以我們不妨從最簡單的例子開始學習一門新的語言。例子不多,但是有代表性。
(a)最簡單的程式碼
[cpp] view plain copy
- package main
- import "fmt"
-
- func main() {
- fmt.Println("hello, world")
- }
(b)基本的函式
[cpp] view plain copy
- package main
- import "fmt"
- func sub(a int, b int) int {
- return a - b;
- }
- func main() {
- fmt.Println(sub(2, 3))
- }
(c)if語句學習
[cpp] view plain copy
- package main
- import "fmt"
- func compare(a int, b int) {
- if(a > b) {
- fmt.Println("greater")
- }else{
- fmt.Println("smaller")
- }
- }
- func main() {
- compare(3, 2)
- }
(d)switch語句學習
[cpp] view plain copy
- package main
- import "fmt"
- func test(a int) {
- switch (a) {
- case 1:
- fmt.Println("1")
- case 2:
- fmt.Println("2")
- default:
- fmt.Println("error")
- }
- }
- func main() {
- test(1)
- test(2)
- test(3)
- }
(e)迴圈語句學習
[cpp] view plain copy
- package main
- import "fmt"
- func show(data int) {
- var index int
- index = 0
- for {
- if(index >= data) {
- break
- }
- fmt.Println(index)
- index ++
- continue
- }
- }
- func main() {
- show(10)
- }
(f)結構體學習
[cpp] view plain copy
- package main
- import "fmt"
- type node struct {
- data int
- }
- func(p* node)set(val int)() {
- p.data = val
- }
- func(p* node)get() int {
- return p.data;
- }
- func main() {
- n := node{data: 10}
- m := &n
- m.set(12)
- fmt.Println(m.get())
- }