Go语言(Golang)是一种静态类型、编译型、并发性强的编程语言,由Google开发。以下是Go语言的一些基本语法格式:
包声明
:每个Go文件都以包声明开始。
package main
导入语句
:用来导入其他包。
import “fmt”
变量声明
:使用
var
关键字声明变量。
var message string = “Hello, World!”
常量声明
:使用
const
关键字声明常量。
const Pi = 3.14159
基本数据类型
:
整型:
int
,
int8
,
int32
,
int64
等。
浮点型:
float32
,
float64
。
布尔型:
bool
。
字符串:
string
。
复数:
complex64
,
complex128
。
类型转换
:使用
type
关键字进行类型转换。
var f float64 = 3.0
var i int = int(f)
控制结构
:
if语句
:
if x > 0 {
fmt.Println(“x is positive”)
} else {
fmt.Println(“x is non-positive”)
}
for循环
:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
switch语句
:
switch day := time.Now().Weekday(); day {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
函数
:使用
func
关键字定义函数。
func sayHello(name string) {
fmt.Println("Hello,", name)
}
数组和切片
:
数组
:
var arr [5]int
切片
:
slice := []int{2, 4, 6, 8}
映射(Map)
:
map := make(map[string]int)
map["key"] = 10
结构体(Struct)
:
type Vertex struct {
X, Y float64
}
接口(Interface)
:
type Reader interface {
Read(p []byte) (n int, err error)
}
并发编程
:
goroutine
:使用
go
关键字启动一个新的goroutine。
go sayHello("World")
通道(Channel)
:用于在goroutines之间安全地传递数据。
ch := make(chan int)
go func(ch chan int) {
ch <- 1
}(ch)
错误处理
:使用
error
类型处理错误。
if _, err := strconv.Atoi("-12345"); err != nil {
fmt.Println(err)
}
注释
:
单行注释:
// This is a comment
多行注释:
/* This is a comment
that spans multiple lines. */
Go语言的语法简洁,易于学习。以上是Go语言的一些基本语法,但Go语言还有很多高级特性和细节,建议阅读官方文档或相关书籍以获得更深入的理解。