GoLangStudy:day5

📅 2026/7/11 0:21:56 👁️ 阅读次数 📝 编程学习
GoLangStudy:day5

GoLangStudy:day5

GO day5

golang语法注意点(map与struct,面向对象起步)

1.map的常见使用方式

以下是map的增删改查:

package mainimport "fmt"// map与slice一样,传参时为引用传递,这是因为map与slice本质上都是指针
func PrintMap(citymap map[string]string) {//map的遍历for key, value := range citymap {fmt.Println("key = ", key, "value = ", value)}
}func main() {//增citymap := make(map[string]string)citymap["one"] = "one"citymap["two"] = "two"citymap["three"] = "three"PrintMap(citymap)fmt.Println("------------------")//删delete(citymap, "two")PrintMap(citymap)fmt.Println("------------------")//改citymap["three"] = "UBW"PrintMap(citymap)
}

输出结果:

key =  one value =  one
key =  two value =  two
key =  three value =  three
------------------
key =  one value =  one
key =  three value =  three
------------------
key =  one value =  one
key =  three value =  UBW

想要复制一个map时,直接新建一个空map,然后遍历赋值

2.struct的定义与使用

package mainimport "fmt"// 定义结构体,与C++中声明类差不多
type Book struct {name   stringauthor string
}// 由于这里是值传递,这种修改不会起作用
func changeBook(book Book) {book.name = "faker"
}// 使用指针传递,修改才会真正起作用
func changingBook(book *Book) {book.name = "faker"
}func main() {var book1 Book//为结构体对象赋值book1.name = "C++"book1.author = "flora2"fmt.Printf("book1=%v\n", book1)fmt.Println("------------------")//值传递changeBook(book1)fmt.Printf("book1=%v\n", book1)fmt.Println("------------------")//指针传递changingBook(&book1)fmt.Printf("book1=%v\n", book1)
}

输出结果:

book1={C++ flora2}
------------------
book1={C++ flora2}
------------------
book1={faker flora2}

3.面向对象:类的表示与封装

在golang中,struct可以看做没有方法的类,需要在结构体外部定义方法来使用

示例:

package mainimport "fmt"type Book struct {title  stringauthor stringprice  int
}// 对Book类所属方法的声明形式:
//在方法名前面绑定所属类,一定要加指针形式!!!!this表示使用此方法的对象
// 修改对象属性
func (this *Book) changePrice(newp int) {this.price = newp
}// 返回对象的某个属性
func (this *Book) getName() string {return this.title
}// 打印对象
func (this *Book) ShowBook() {fmt.Println("title: ", this.title)fmt.Println("author: ", this.author)fmt.Println("price: ", this.price)
}func main() {//创建一个新对象book1 := Book{"Isaac", "momlove", 99}book1.ShowBook()fmt.Println("--------------------")book1.changePrice(1)book1.ShowBook()fmt.Println("--------------------")
}

输出结果:

title:  Isaac
author:  momlove
price:  99
--------------------
title:  Isaac
author:  momlove
price:  1
--------------------

对于golang的面向对象,结构体名称首字母大写以及结构体内属性首字母为大写等等情况,表示这些都是公有制,包外也可以调用,反之则是私有制,只能在包内定义并使用