Golang实践:程序结构、数据类型
程序结构
名称
25个关键字
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
预声明的常量、类型和函数
- 常量
true false iota nil
- 类型
int int8 int16 int32 int64
unit uint8 uint16 uint32 uint64 uintptr
float32 float64 complex64 complex128
bool byte rune string error
- 函数
make len cap new append copy
close
delete
complex real imag
panic recover
声明
4个主要的声明:
-
变量:var
-
常量:const
-
类型:type
-
函数:func
变量
通用的形式:
var name type = expression
type和expression可以省略一个,但不能都省略
短变量声明
name := expression
短变量声明最少声明一个新变量
指针
flag包的使用:实现echo命令:
package main
import (
"flag"
"fmt"
"strings"
)
var sep = flag.String("s", " ", "separator")
var n = flag.Bool("n", false, "omit trailing newline")
func main() {
flag.Parse()
fmt.Print(strings.Join(flag.Args(), *sep))
if !*n {
fmt.Println()
}
}
赋值
赋值语句用来更新变量所指的值
多重赋值
允许几个变量一次性被赋值
gcd := func(x, y int) int{
for y != 0{
x, y = y, x%y
}
return x
}
res := gcd(10, 5)
func Fib(n int) int {
x, y := 0, 1
for i := 0; i < n; i++ {
x, y = y, x+y
}
return x
}
可赋值性
赋值只有在值对于变量类型是可赋值的时才合法
类型声明
变量或表达式的类型定义这些应有的特性;
很多类型都有一个String方法,在变量通过fmt包作为字符串输出时,它可以控制类型值的显示方式
包和文件
包的作用和其他语言中的库或模块作用类似,用于支持模块化、封装、编译隔离和重用;
package tempconv
import "fmt"
type Celsius float64
type Fahrenheit float64
const (
AbsoluteZeroC Celsius = -273.15
FreezingC Celsius = 0
BoilingC Celsius = 0
)
func (c Celsius) String() string {
return fmt.Sprintf("%gC", c)
}
func (f Fahrenheit) String() string {
return fmt.Sprintf("%gF", f)
}
func CToF(c Celsius) Fahrenheit {
return Fahrenheit(c*9/5 + 32)
}
func FToC(f Fahrenheit) Celsius {
return Celsius((f - 32) * 5 / 9)
}
tempconv.CToF()
tempconv.FToC()
导入
在Go程序里,每一个包通过称为“导入路径”(import path)的唯一字符串来标识;
如果导入一个没有被引用的包,就会触发一个错误;这个检查帮助消除代码演进过程中不再需要的依赖;
包初始化
包的初始化从初始化级别的变量开始,这些变量按照声明顺序初始化,在依赖已解析完毕的情况下,根据依赖的顺序进行;
作用域
声明将名字和程序实体关联起来,如一个函数或一个变量; 声明的作用域是指用到声明时所声明名字的源代码段;
debug “exit status 1” error when running exec.Command
How to debug “exit status 1” error when running exec.Command in Golang
The solution is to use the Stderr property of the Command object. This can be done like this:
cmd := exec.Command("find", "/", "-maxdepth", "1", "-exec", "wc", "-c", "{}", "\\")
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
return
}
fmt.Println("Result: " + out.String())
refs
《The Go Programming Language》Alan A.A, Donovan & Brian W.Kernighan