Go代码规范
规范代码风格
1、正确的注释和注释风格
1)Go官方推荐使用行注释来注释整个方法和语句
2、正确的代码缩进和空白
1)使用一次tab操作,实现缩进,默认整体向右移动,向左移动可以用 shift+tab
如下图:
shift+tab
tab
2)或者使用gofmt来进行格式化
1、先打乱代码

2、gofmt main.go

3、然后打开后,我们发现只是在命令行格式化并输出,源文件中并没有对齐
4、通过 gofmt -w main.go 指令先格式化后再写入源文件中,就可以看到对齐后的代码

3)运算符中两边习惯性各加一个空格:比如 3 + 4 * 5

3、Go语言的代码风格
package main
import "fmt"
func main(){
fmt.Println("hello,world!")
}
上面的写法正确
package main
import "fmt"
func main() //错误的写法
{
fmt.Println("hello,world!")
}
这种写法是错误的,Go语言中不允许这样编写
4、一行最长不超过80个字符,超过的请使用换行展示,尽量保持格式优雅
示例:
fmt.Println("helloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworld")
上面这一行代码都写在一行,后面再写代码语句的话会报错
解决方式:
fmt.Println("helloworldhelloworldhelloworldhelloworldhelloworldhelloworldhellowor", "ldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworld", "helloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhel","loworld")
用","来换行拼接,有点类似于java、C#中的"+"来拼接字符串。

浙公网安备 33010602011771号