Magic go language (basic syntax)
[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
Learning a new language begins with the basic syntax. After all, it is boring to use grammar books to learn a language. Therefore, we may wish to start learning a new language from the simplest example. There are not many examples, but they are representative.
(A) simplest code
package mainimport "fmt"func main() { fmt.Println("hello, world")}
(B) Basic functions
package mainimport "fmt"func sub(a int, b int) int { return a - b;}func main() { fmt.Println(sub(2, 3))}
(C) if statement Learning
package mainimport "fmt"func compare(a int, b int) { if(a > b) { fmt.Println("greater") }else{ fmt.Println("smaller") }}func main() { compare(3, 2)}
(D) switch statement Learning
package mainimport "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) loop statement Learning
package mainimport "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) structured learning
package mainimport "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())}
Let's talk about so much. Next time we will introduce some advanced functions.