一、变量定义
package main
import (
"fmt"
"math"
"math/cmplx"
)
var (
aa = 3
ss = "kkk"
bb = true
)
func variableZeroValue() {
var a int
var s string
fmt.Printf("%d %q\n", a, s)
}
func variableInitialValue() {
var a, b int = 3, 4
var s string = "abc"
fmt.Println(a, b, s)
}
func variableTypeDeduction() {
var a, b, c, s = 3, 4, true, "def"
fmt.Println(a, b, c, s)
}
func variableShorter() {
a, b, c, s := 3, 4, true, "def"
b = 5
fmt.Println(a, b, c, s)
}
func euler() {
fmt.Printf("%.3f\n",
cmplx.Exp(1i*math.Pi)+1)
}
func triangle() {
var a, b int = 3, 4
fmt.Println(calcTriangle(a, b))
}
func calcTriangle(a, b int) int {
var c int
c = int(math.Sqrt(float64(a*a + b*b)))
return c
}
func consts() {
const (
filename = "abc.txt"
a, b = 3, 4
)
var c int
c = int(math.Sqrt(a*a + b*b))
fmt.Println(filename, c)
}
func enums() {
const (
cpp = iota
_
python
golang
javascript
)
const (
b = 1 << (10 * iota)
kb
mb
gb
tb
pb
)
fmt.Println(cpp, javascript, python, golang)
fmt.Println(b, kb, mb, gb, tb, pb)
}
func main() {
fmt.Println("Hello world")
variableZeroValue()
variableInitialValue()
variableTypeDeduction()
variableShorter()
fmt.Println(aa, ss, bb)
euler()
triangle()
consts()
enums()
}
二、switch、if
package main
import (
"fmt"
"io/ioutil"
)
func grade(score int) string {//switch不需要break,且可以加入条件判断
g := ""
switch {
case score < 0 || score > 100:
panic(fmt.Sprintf(
"Wrong score: %d", score))
case score < 60:
g = "F"
case score < 80:
g = "C"
case score < 90:
g = "B"
case score <= 100:
g = "A"
}
return g
}
func main() {
// If "abc.txt" is not found,
// please check what current directory is,
// and change filename accordingly.
const filename = "abc.txt"
if contents, err := ioutil.ReadFile(filename); err != nil {//if不需要括号,且可以写两个语句
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
fmt.Println(
grade(0),
grade(59),
grade(60),
grade(82),
grade(99),
grade(100),
// Uncomment to see it panics.
// grade(-3),
)
}
三、for
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
func convertToBin(n int) string {
result := ""
for ; n > 0; n /= 2 {//一个判断,一个赋值
lsb := n % 2
result = strconv.Itoa(lsb) + result
}
return result
}
func printFile(filename string) {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
printFileContents(file)
}
func printFileContents(reader io.Reader) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {//一个判断,循环
fmt.Println(scanner.Text())
}
}
func forever() {
for {//死循环
fmt.Println("abc")
}
}
func main() {
fmt.Println("convertToBin results:")
fmt.Println(
convertToBin(5), // 101
convertToBin(13), // 1101
convertToBin(72387885),
convertToBin(0),
)
fmt.Println("abc.txt contents:")
printFile("basic/branch/abc.txt")
fmt.Println("printing a string:")
s := `abc"d"
kkkk
123
p`
printFileContents(strings.NewReader(s))
// Uncomment to see it runs forever
// forever()
}
四、函数
package main
import (
"fmt"
"math"
"reflect"
"runtime"
)
func eval(a, b int, op string) (int, error) {//返回两个值
switch op {
case "+":
return a + b, nil
case "-":
return a - b, nil
case "*":
return a * b, nil
case "/":
q, _ := div(a, b)//第二值不使用,所以用_代替
return q, nil
default:
return 0, fmt.Errorf(
"unsupported operation: %s", op)
}
}
func div(a, b int) (q, r int) {//定义了返回两个值的名字,调用函数时编译器可自动推断出来
return a / b, a % b
}
func apply(op func(int, int) int, a, b int) int {//函数作为参数
p := reflect.ValueOf(op).Pointer()
opName := runtime.FuncForPC(p).Name()
fmt.Printf("Calling function %s with args "+
"(%d, %d)\n", opName, a, b)
return op(a, b)
}
func sum(numbers ...int) int {
s := 0
for i := range numbers {
s += numbers[i]
}
return s
}
func swap(a, b int) (int, int) {
return b, a
}
func main() {
fmt.Println("Error handling")
if result, err := eval(3, 4, "x"); err != nil {//if语法
fmt.Println("Error:", err)
} else {
fmt.Println(result)
}
q, r := div(13, 3)
fmt.Printf("13 div 3 is %d mod %d\n", q, r)
fmt.Println("pow(3, 4) is:", apply(//匿名函数
func(a int, b int) int {
return int(math.Pow(
float64(a), float64(b)))
}, 3, 4))
fmt.Println("1+2+...+5 =", sum(1, 2, 3, 4, 5))
a, b := 3, 4
a, b = swap(a, b)//值传递
fmt.Println("a, b after swap is:", a, b)
}