在Go语言(通常称为Golang)中,声明是用来定义变量、常量、类型、函数、方法和接口的语法结构。以下是一些常见的Go语言声明示例:
变量声明:
var a int
var b = 10 // 同时声明和初始化
var c int = 20 // 声明并初始化
常量声明:
const pi = 3.14159
类型声明:
type Kilometers float64
函数声明:
func add(x int, y int) int {
return x + y
}
方法声明(在结构体上定义的方法): “`go type Point struct { X, Y float64 }
func (p *Point) Scale(factor float64) {
p.X *= factor
p.Y *= factor
}
6. **接口声明**:
```go
type Reader interface {
Read(p []byte) (n int, err error)
Close() error
}
导入包:
import "fmt"
包声明(在每个Go文件的开头):
package main
声明是Go语言编程的基础,它们定义了程序的结构和行为。每个声明都遵循特定的语法规则,以确保代码的清晰和一致性。