在Mac OS系统中编写第一个Go程序----Hello World
在Mac OS系统中,打开终端。创建一个用于存储这个程序的文件夹,如下输入:mkdir -p $GOPATH/src/github.com/[github username]/hello
在Mac OS系统中,打开终端。
创建一个用于存储这个程序的文件夹,输入如下:
mkdir -p $GOPATH/src/github.com/[your github username]/hello
切换到Hello文件夹,输入如下:
cd $GOPATH/src/github.com/[your github username]/hello
使用vim软件编写代码,在文件夹hello中,创建一个名为main.go的文件,输入如下。
vim main.go
启动vim,进入了命令模式,直接按下“i”键,切换到输入模式。
编写代码如下:
package main //main包是Go程序的入口包
import( //导入包
"fmt"
)
func main(){ //程序执行的入口函数main()。
fmt.Println("Hello World!")
}
输入完成代码以后,按下“esc”键,退出输入模式,切换到命令模式。
在命令模式情况下,保存main.go,并退出vim,先,输入如下:
:wq
退出vim以后,使用go run编译并运行程序,输入如下:
go run main.go
如编译输出可执行文件,使用如下指令可以将这段代码编译为可执行文件:
go build ./main.go
代码格式化工具gofmt
输入以下代码:
package main
import ("fmt")
func main() {
a:=1
if(a>=1){fmt.Println(a)}
}
输入命令行如下:
gofmt test.go
运行结果如下:
package main
import (
"fmt"
)
func main() {
a := 1
if a >= 1 {
fmt.Println(a)
}
}
如果需要直接优化后保存到原来的代码文件中,可以在运行gofmt的时间加上-w命令参数:
gofmt -w test.go
gofmt --help输出下面的信息:
usage: gofmt [flags] [path ...]
-cpuprofile string
write cpu profile to this file
-d display diffs instead of rewriting files
-e report all errors (not just the first 10 on different lines)
-l list files whose formatting differs from gofmt's
-r string
rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')
-s simplify code
-w write result to (source) file instead of stdout
更多推荐
所有评论(0)