Go语言常见语法错误
1、开大括号不能放在单独的一行
错误代码:
package main
import "fmt"
func main()
{
fmt.Println("hello world!")
}
编译错误:
./main.go:5:6: missing function body for “main”
./main.go:6:1: syntax error: unexpected semicolon or newline before {
正确代码:
package main
import "fmt"
func main() {
fmt.Println("hello world!")
}
2、未使用的变量
如果你有未使用的局部变量,代码将编译失败。
如果你给未使用的变量分配了一个新的值,代码还是会编译失败。你需要在某个地方使用这个变量,才能让编译器愉快的编译。
错误代码:
package main
var gvar int
func main() {
var one int
two := 2
var three int
three = 3
}
编译错误:
./main.go:6:6: one declared and not used
./main.go:7:9: two declared and not used
./main.go:8:6: three declared and not used
正确代码:
package main
import "fmt"
func main() {
var one int
_ = one
two := 2
fmt.Println(two)
var three int
three = 3
one = three
var four int
four = four
}
// 另外可以选择是注释掉或者移除未使用的变量
3、未使用的Imports
如果你引入一个包,而没有使用其中的任何函数、接口、结构体或者变量的话,代码将会编译失败。
如果你真的需要引入的包,你可以添加一个"_"下划线标记符,来作为这个包的名字,从而避免编译失败。下滑线标记符用于引入,但不使用。
错误代码:
package main
import (
"fmt"
"log"
"time"
)
func main() {
}
编译错误: