关键字或保留字是语言中用于某些内部过程或代表某些预定义操作的词。因此,不允许将这些词用作标识符。这样做会导致编译时错误。
例子:
// Go program to illustrate the
// use of keywords
package main
import "fmt"
// Here, package, import, func,
// var are keywords
func main() {
// Here, a is a valid identifier
var a = "GeeksforGeeks"
fmt.Println(a)
// Here, the default is an
// illegal identifier and
// compiler will throw an error
// var default = "GFG"
}
输出:
GeeksforGeeks
Go 语言中共有 25 个关键字,如下所示:
break |
case |
chan |
const |
continue |
default |
defer |
else |
fallthrough |
for |
func |
go |
goto |
if |
import |
interface |
map |
package |
range |
return |
select |
struct |
switch |
type |
var |
例子:
// Go program to illustrate
// the use of keywords
// Here package keyword is used to
// include main package in the program
package main
// import keyword is used to
// import "fmt" in your package
import "fmt"
// func is used to
// create function
func main() {
// Here, var keyword is used
// to create variables
// Pname, Lname, and Cname
// are the valid identifiers
var Pname = "GeeksforGeeks"
var Lname = "Go Language"
var Cname = "Keywords"
fmt.Printf("Portal name: %s", Pname)
fmt.Printf("\nLanguage name: %s", Lname)
fmt.Printf("\nChapter name: %s", Cname)
}
输出:
Portal name: GeeksforGeeks
Language name: Go Language
Chapter name: Keywords