本文列出简单的代码片段及基础知识。
简单说明
包
import的包从src算,如果在子目录,一定要添加子目录路径。如import “a”,则a一定在src目录下。
同一个目录只能有一个包名。但可以有多个文件(使用同一包名)。
没有被使用的包,要删除或注释,否则编译不通过。
包目录不能与系统包名相同,如系统有sync包,不能再创建sync目录。
除for等外,逗号不是必须的,看个人习惯。
没有使用的变量,编译不通过。
测试
文件名带_test
的是测试专用,不能用go run
来执行。
编码小结
打印:
1 2 3 4 5 6 7
| fmt.Printfln("Hello world"); fmt.Printf("Hello %v\n", "world");
a := "12345" fmt.Printf("% x", a) // 31 32 33 34 35 fmt.Printf("%q", a) // "12345"
|
如果打印/组装的字符串过多,可用’`‘替换双引号。
打印变量类型:
1 2 3
| 引入包: "reflect" fmt.Println(reflect.TypeOf(var))
|
组装字符串示例:
1 2 3 4 5
|
return fmt.Sprintf("%.4v%.2v%.2v%.2v%.2v%.2v", year, month, day, hour, minute, seconds);
|
1 2 3 4 5 6 7 8 9 10
| value := ` 此处顶格写,否则会有空格 此后符号不用另一行,否则默认会有换行`
value := ` 不顶格写,有空格 后面有换行 `
|
代码片段(用以切换语言时看):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| 有传入、输出参数 func sqrt(x float64) float64 { ret := 1.0 for i := 0; i < 10; i++ { ret = ret - (ret*ret - x) / 2 / ret } return ret }
"类" package class
import ( "fmt" )
type SimpleClass struct { }
func (p *SimpleClass) printf() { fmt.Printf("%v\n", "hello world"); }
func SimpleTest() {
c := SimpleClass{}; c.printf(); }
主函数文件: package main
import ( "class" ) func main() { class.SimpleTest(); }
if bit0 == 0 { return 'I'; } else if bit0 == 1 && bit1 == 0 { return 'S'; } else if bit0 == 1 && bit1 == 1 { return 'U'; } else { return 0; }
|
同一程序代码,生成不同文件执行不同函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import ( "fmt" "os" "path/filepath" "strings" )
func main() { filename := filepath.Base(os.Args[0]) if strings.Contains(filename, "send") { send() } else if strings.Contains(filename, "recv") { recv() } else { fmt.Println("do nothing") } }
|
通过编译命令传递参数。
如编译时间,golang 不支持,可以嵌入 C 语言实现,也可以用脚本获取时间,再通过编译命令传递。
命令选项为-ldflags "-X '<包名>.<变量名>=值'
代码:
1 2 3 4 5 6 7 8 9
| var ( BuildTime string Version string )
func getVersion() string { return fmt.Sprintf(" %v build: %v\n", Version, BuildTime) }
|
脚本:
1 2 3 4 5 6 7 8 9 10
| Version="v1.0" BuildTime=`date +'%Y-%m-%d %H:%M:%S'`
# 写到文件方式 #echo "package cmd" > cmd/ver.go #echo "const BuildTime1 = \"${BuildTime}\"" >> cmd/ver.go #echo "const Version1 = \"${Version}\"" >> cmd/ver.go
# 参数传递方式 GO111MODULE=on go build -ldflags "-X 'github.com/latelee/cmdtool/cmd.BuildTime=${BuildTime}' -X 'github.com/latelee/cmdtool/cmd.Version=${Version}'" -mod vendor -o cmdtool.exe main.go
|
不定长参数传递
1 2 3 4 5 6 7 8 9 10 11 12 13
| func foo(str ...string) { for _, v := range a { fmt.Println(v) } }
func callit(str ...string) { foo(str...) }
func main() { callit("f", "a") }
|