13.数组的使用
func main() {
var arr = [5]int{1, 2, 3, 4, 5}
for i := 0; i < 5; i++ {
fmt.Println(arr[i])
}
}
14.多维数组的使用
func main() {
var arr = [2][2]int{{1, 2}, {3, 4}}
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
fmt.Print(arr[i][j])
}
fmt.Println()
}
}
15.数组与切片作为参数传递
func main() {
b := [...]int{1, 2, 3, 4, 5}
bb(b)
fmt.Println(b)
c := []int{1, 2, 3, 4, 5}
cc(c)
fmt.Println(c)
}
func bb(b [5]int) {
b[0], b[len(b)-1] = b[len(b)-1], b[0] //交换数组首尾的值
}
func cc(c []int) {
c[0], c[len(c)-1] = c[len(c)-1], c[0] //交换数组首尾的值
}
分析:数组作为参数传递时,是值传递;切片作为参数传递时,是引用传递
16.指针的使用
func main() {
var p *int
var a int = 5
p = &a
fmt.Printf("%x", p)
}
17.结构体的使用
type Book struct {
title string
author string
book_id int
}
func main() {
var book1 Book
book1.title = "C++"
book1.author = "peng"
book1.book_id = 1
fmt.Println(book1)
fmt.Println(Book{title: "Java", author: "peng", book_id: 2}) //匿名结构体
}
18.结构体作为参数传递
type Book struct {
title string
author string
book_id int
}
func changeBook1(book Book) {
book.title = "HHH"
}
func changeBook2(book *Book) {
book.title = "HHH"
}
func main() {
var book1 Book
book1.title = "C++"
book1.author = "peng"
book1.book_id = 1
changeBook1(book1)
fmt.Println(book1)
changeBook2(&book1)
fmt.Println(book1)
}
分析:如果想在函数中改变结构体的值,必须传入结构体的指针
19.结构体的方法
type Rect struct {
width, height float64
}
func (r *Rect) Area() float64 {
return r.height * r.width
}
func main() {
var r Rect
r.width = 10
r.height = 10
fmt.Println(r.Area())
}