flora222

GoLangStudy:day5

GO day5

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

1.map的常见使用方式

以下是map的增删改查:

package main

import "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 main

import "fmt"

// 定义结构体,与C++中声明类差不多
type Book struct {
	name   string
	author 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 main

import "fmt"

type Book struct {
	title  string
	author string
	price  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的面向对象,结构体名称首字母大写以及结构体内属性首字母为大写等等情况,表示这些都是公有制,包外也可以调用,反之则是私有制,只能在包内定义并使用

posted on 2026-07-11 00:02  Flora2  阅读(5)  评论(0)    收藏  举报

导航